新手求助:如何用Python发送application/x-www-form-urlencoded格式的POST请求?
Hey there! Since you're new to Python, let's walk through exactly how to send that POST request you shared. I'll cover two common methods: one using Python's built-in tools (no extra installs required) and another with the popular requests library (way simpler for beginners).
First, let's recap the key details from your request example:
- Target URL:
http://www.chilkatsoft.com/httpTest/cityCountry.asp - Request method: POST
- Content-Type:
application/x-www-form-urlencoded - Form data:
city=Paris&country=France
Using the requests Library (Recommended for Beginners)
This is the most straightforward method. First, you'll need to install the library if you haven't already:
pip install requests
Then, here's the code to send your request:
import requests # Define the target URL url = "http://www.chilkatsoft.com/httpTest/cityCountry.asp" # Define your form data as a dictionary (requests will handle encoding it correctly) form_data = { "city": "Paris", "country": "France" } # Send the POST request response = requests.post(url, data=form_data) # Check the response print("Response Status Code:", response.status_code) print("Response Content:", response.text)
What's happening here?
- The
dataparameter automatically sets theContent-Typeheader toapplication/x-www-form-urlencodedand encodes your dictionary into thecity=Paris&country=Franceformat. response.status_codetells you if the request succeeded (200 means success).response.textgives you the raw content returned by the server.
Using Python's Built-in urllib Module
If you don't want to install any extra libraries, you can use Python's built-in urllib modules. The code is a bit more verbose, but it works out of the box:
import urllib.request import urllib.parse # Define the target URL url = "http://www.chilkatsoft.com/httpTest/cityCountry.asp" # Encode the form data into the required format form_data = urllib.parse.urlencode({ "city": "Paris", "country": "France" }).encode("utf-8") # Create the request object with the correct headers request = urllib.request.Request(url, data=form_data, method="POST") request.add_header("Content-Type", "application/x-www-form-urlencoded") # Send the request and get the response with urllib.request.urlopen(request) as response: print("Response Status Code:", response.getcode()) print("Response Content:", response.read().decode("utf-8"))
What's happening here?
urllib.parse.urlencode()converts the dictionary into thecity=Paris&country=Francestring, then we encode it to bytes with.encode("utf-8")(required for sending over HTTP).- We manually set the
Content-Typeheader sinceurllibdoesn't do this automatically. urlopen()sends the request, and we read and decode the response to get human-readable text.
Either of these methods will send the exact POST request you provided. I'd recommend starting with requests since it's much easier to read and maintain as you learn more Python!
内容的提问来源于stack exchange,提问作者BeNice

