开发者

How to use python urllib2 to send json data for login

I want to use python urllib2 to simulate a login action, I use Fiddler to catch th开发者_StackOverflowe 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...


For Python 3.x

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)

Example

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)


import urllib2
import json
# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)

This assumes you're using HTTP POST to send a simple json object with username and password.


You can specify data upon request:

import urllib
import urllib2

url = 'http://example.com/login'
values = YOUR_CREDENTIALS_JSON

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()


You can use the 'requests' python library to achieve this:

http://docs.python-requests.org/en/latest/index.html

You will find this example:

http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests (More complicated POST requests)

>>> import requests
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)

It seems python do not set good headers when you are trying to send JSON instead of urlencoded data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜