Curl工作但不是Python请求

Sha*_*ani 11 python curl python-requests

我正在尝试从http://erdos.sdslabs.co/users/shagun.json获取JSON响应.使用浏览器/ Python的Requests库会导致身份验证错误,但curl似乎工作正常.

curl http://erdos.sdslabs.co/users/shagun.json 
Run Code Online (Sandbox Code Playgroud)

返回JSON响应.

为什么curl请求在普通浏览器或基于请求的请求失败时有效?

Sim*_*ser 11

使用telnet检查:

$ telnet erdos.sdslabs.co 80
Trying 62.141.37.215...
Connected to erdos.sdslabs.co.
Escape character is '^]'.
GET http://erdos.sdslabs.co/users/shagun.json HTTP/1.0

HTTP/1.1 302 Found
Date: Sat, 26 Jul 2014 11:18:58 GMT
Server: Apache
Set-Cookie: PHPSESSID=juvg7vrg3vs4t00om3a95m4sc7; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: /login
Access-Control-Allow-Origin: http://erdos.sdslabs.co
X-Powered-By: PleskLin
Content-Length: 1449
Connection: close
Content-Type: application/json

{"email":"sshagun.sodhani@gmail.com","username":"shagun","name":"Shagun      
[...]
Run Code Online (Sandbox Code Playgroud)

我们看到Web服务器正在响应302 - 重定向到Location/login.请求和Web浏览器都遵循这一点,并达到登录提示.但是,我们看到Web服务器也在响应您正在使用的json,而curl(和telnet)非常简单,只能接受该数据.

最佳做法是修复Web服务器,使其既不需要您登录,也不会在要求用户登录的同时不提供受密码保护的数据.

如果您无法更改Web服务器,则可以告知请求模块忽略重定向:

import requests
result = requests.get('http://erdos.sdslabs.co/users/shagun.json', allow_redirects=False)
print result.content
Run Code Online (Sandbox Code Playgroud)


Den*_*zov 8

对于像我这样的已故谷歌用户:

就我而言,问题是我使用requests.get(url, data={...}). 修改为 后requests.get(url, params={...}),问题解决。

  • 这正是我的情况,现在可以了,谢谢!我想我已经在 POST 和 GET 之间来回更改了,但没有意识到它们使用不同的参数名称。 (3认同)