curl u和python请求之间有区别吗

2024-10-01 00:26:04 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想检索一个网页python.Requests

https://ororo.tv/api/v2/episodes/9

这需要基本身份验证。如果我像这样卷曲

 curl -u test@example.com:password https://ororo.tv/api/v2/episodes/9

但是,当我尝试在python中使用Requests库执行相同的操作时,我得到了我想要的响应,如下所示

^{pr2}$

我总是收到520个回复。有人能告诉我,我可能做错了什么吗?在


Tags: httpstestcom身份验证api网页examplepassword
2条回答

当使用类似Python请求的东西时,您尝试使用的api可能要求您以特定的方式格式化请求,可能需要头和base64编码的身份验证。在

查看这个示例,它将向您展示如何同时发送base64编码的身份验证头以及一些数据:

import requests
import base64

username = "some_username"
password = "some_password"

request_url = "https://ororo.tv/api/v2/episodes/9"

# In this example, I'm passing some data along with the request.
# these are generally what you would expect to pass along in an encoded url:
# /api?some_url_param_key=some_url_param_value

data = {}
data["some_url_param_key"] = "some_url_param_value"

# This is an example header, not necessarily what you need, 
# but it should serve as a good starting point.

headers = {}
headers["Authorization"] = "Basic " + base64.encodestring(username + ":" + password).replace('\n', '')
headers["Accept"] = "*/*"
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["User-Agent"] = "runscope/0.1"

# You can use post() in some cases where you would expect to use get().
# Every API is its own unique snowflake and expects different inputs.
# Try opening up the Chrome console and run the request in the 
# browser, where you know it works. Examine the headers and response
# in cases where the API you're accessing doesn't provide you 
# with the necessary inputs. 

result = requests.post(request_url, headers=headers, data=data)
print result

是的,有细微的区别。在发送的头文件中有一些细微的差别,这些显然对这个API很重要。在

如果您将查询的URL更改为使用http://httpbin.org/get(联机HTTP test service HTTPBin.org的端点),您可以看到curl和{}发送的内容之间的区别:

$ curl -u test@example.com:password http://httpbin.org/get
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Authorization": "Basic dGVzdEBleGFtcGxlLmNvbTpwYXNzd29yZA==",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.51.0"
  },
  "origin": "84.92.98.170",
  "url": "http://httpbin.org/get"
}
$ python -c "import requests; print(requests.get('http://httpbin.org/get', auth=('test@example.com', 'password')).text)"
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Authorization": "Basic dGVzdEBleGFtcGxlLmNvbTpwYXNzd29yZA==",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.11.1"
  },
  "origin": "84.92.98.170",
  "url": "http://httpbin.org/get"
}

要突出差异:

  • requests发送一个额外的头,Accept-Encoding,设置为gzip, deflate
  • User-Agent标头不同;两者都反映当前代理。在

您必须查看这些标题中的哪一个导致了https://ororo.tv/api/v2站点上的问题。当我更正URL以使用v2https时,就像curl命令,设置User-Agent头,那么我得到一个有效的响应:

^{pr2}$

相关问题 更多 >