我在Python 2.7中使用urllib及其工作时有以下代码。我正在尝试使用请求库执行相同的请求,但我无法让它工作。
import urllib
import urllib2
import json
req = urllib2.Request(url='https://testone.limequery.com/index.php/admin/remotecontrol',\
data='{\"method\":\"get_session_key\",\"params\":[\"username\",\"password\"],\"id\":1}')
req.add_header('content-type', 'application/json')
req.add_header('connection', 'Keep-Alive')
f = urllib2.urlopen(req)
myretun = f.read()
j=json.loads(myretun)
print(j['result'])
使用请求库(不起作用)
import requests
import json
d= {"method":"get_session_key","params":["username","password"],"id":"1"}
headers = {'content-type' :'application/json','connection': 'Keep-Alive'}
req2 = requests.get(url='https://testone.limequery.com/index.php/admin/remotecontrol',data=d,headers=headers)
json_data = json.loads(req2.text)
print(json data['result'])
我收到错误JSONDecodeError: Expecting value: line 1 column 1 (char 0)
如何使代码与请求库一起工作?
首先,您发送了错误类型的请求。您正在发送GET请求,但您需要使用requests.post
发送POST。
其次,将字典作为data
传递将对数据进行格式编码,而不是对其进行JSON编码。如果要在请求体中使用JSON,请使用json
参数,而不是data
:
requests.post(url=..., json=d)
参考链接:http://docs.python-requests.org/en/master/api/
你可以像这样使用python的请求模块
import requests
Req = requests.request(
method = "GET", # or "POST", "PUT", "DELETE", "PATCH" etcetera
url = "http(s)://*",
params = {"key": "value"}, # IF GET Request (Optional)
data = {"key": "value"}, # IF POST Request (Optional)
headers = {"header_name": "header_value"} # (Optional)
)
print Req.content
您可以使用下面的try :: catch块来包围代码,以捕获请求模块抛出的任何异常
try:
# requests.request(** Arguments)
except requests.exceptions.RequestException as e:
print e
有关完整参数列表,请查看参考链接。