我有一个 curl 请求和一个使用 python 请求模块的类似请求到本地 Web 服务。虽然 curl 请求正常工作,但通过 python 发出的请求没有按预期工作,即没有返回 json 响应。
关于为什么会发生这种情况的任何想法?使用 python 我仍然得到 200 响应,但是得到的是 HTML 响应文本而不是像 curl 中的 json,响应是关于无效 session 等的。
这是curl请求
root@weve1:~$ curl -k --GET --data "ajax=getPermissions&project=test&session.id=5604d7ce-f3dd-4349-8957-563c2675ae5c" http://localhost:12320/manager
{
"permissions" : [ {
"permission" : [ "ADMIN" ],
"username" : "azkaban"
} ],
"project" : "test",
"projectId" : 92
}
这与在 python 中发出的请求相同
root@weve1:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> s=requests.get('http://localhost:12320/manager',data={'ajax':'getPermissions','project':'test','session.id':'5604d7ce-f3dd-4349-8957-563c2675ae5c'})
>>> s.json()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 741, in json
return json.loads(self.text, **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>>
最佳答案
来自 curl 手册页:
-G/--get
When used, this option will make all data specified with -d/--data or --data-binary to be used in a HTTP GET request instead of the POST request that otherwise would be used. The data will be appended to the URL with a '?' separator.
所以 curl 实际上是将参数作为查询字符串传递,即 http://localhost:12320/manager?ajax=getPermissions&project=test&session.id=5604d7ce-f3dd-4349-8957-563c2675ae5c
.
为了通过请求传递URL中的数据,你需要传递数据in the params
argument :
data = { 'ajax': 'getPermissions', 'project': 'test', 'session.id': '5604d7ce-f3dd-4349-8957-563c2675ae5c' }
s = requests.get('http://localhost:12320/manager', params=data)
data
参数仅指实际请求主体。
关于当 curl 工作时,python 请求模块不工作。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125537/