I want to use python urllib2 to simulate a login action, I use Fiddler to catch the packets and got that the login action is just an ajax request and the username and password is sent as json data, but I have no idea how to use urllib2 to send json data, help...
To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
Note the following
In Python 3.x the urllib
and urllib2
modules have been combined. The module is named urllib
. So, remember that urllib
in Python 2.x and urllib
in Python 3.x are DIFFERENT modules.
The POST data for urllib.request.Request
in Python 3 does NOT accept a string (str
) -- you have to pass a bytes
object (or an iterable of bytes
)
pass json
data with POST in Python 3.x
import urllib.request import json json_dict = { 'name': 'some name', 'value': 'some value' } # convert json_dict to JSON json_data = json.dumps(json_dict) # convert str to bytes (ensure encoding is OK) post_data = json_data.encode('utf-8') # we should also say the JSON content type header headers = {} headers['Content-Type'] = 'application/json' # now do the request for a url req = urllib.request.Request(url, post_data, headers) # send the request res = urllib.request.urlopen(req) # res is a file-like object # ...
Finally note that you can ONLY send a POST request if you have SOME data to send.
If you want to do an HTTP POST without sending any data, you should send an empty dict as data.
data_dict = {} post_data = json.dumps(data_dict).encode() req = urllib.request.Request(url, post_data) res = urllib.request.urlopen(req)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With