在python请求中包含多个头

2024-05-11 07:41:22 发布

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

下面是curl中的HTTPS调用

header1="projectName: zhikovapp"
header2="Authorization: Bearer HZCdsf="
bl_url="https://BlazerNpymh.com/api/documents?pdfDate=$today"

curl -s -k -H "$header1" -H "$header2" "$bl_url" 

我想用requests模块编写一个等价的python调用。

header ={
            "projectName": "zhikovapp",
            "Authorization": "Bearer HZCdsf="
        }
response = requests.get(bl_url, headers = header)

但是,请求无效。怎么了?

返回的响应的内容如下所示

<Response [400]>
_content = '{"Message":"The request is invalid."}'
headers = {'Content-Length': '37', 'Access-Control-Allow-Headers': 'projectname, authorization, Content-Type', 'Expires': '-1', 'cacheControlHeader': 'max-age=604800', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Date': 'Sat, 15 Oct 2016 02:41:13 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Content-Type': 'application/json; charset=utf-8'}
reason = 'Bad Request'

我正在使用Python2.7

编辑:Soviut指出一些syntex错误后,我进行了更正。


Tags: urlaccesscontentcurlrequestscontrolallowauthorization
2条回答

request.get()中,^{}参数应该定义为一个字典,一组键/值对。您已经定义了一组字符串(唯一列表)。

你应该像这样声明你的头:

headers = {
    "projectName": "zhikovapp",
    "Authorization": "Bearer HZCdsf="
}
response = requests.get(bl_url, headers=headers)

注意字典中每一行的"key": "value"格式。

编辑:你的Access-Control-Allow-Headers说他们会接受projectnameauthorization小写。您已经用大写字母命名了头projectNameAuthorization。如果不匹配,就会被拒绝。

  1. 如果您在进行curl调用的shell中定义了$today,并且没有在requests的调用URL中替换它,那么这可能是导致400错误请求的原因。
  2. Access-Control-*和其他CORS头与非浏览器客户端无关。此外,HTTP头通常不区分大小写。
  3. 以下是@furas的建议:

    $ curl -H "projectName: zhikovapp" -H "Authorization: Bearer HZCdsf=" \
        http://httpbin.org/get
    
    {
       "args": {}, 
       "headers": {
          "Accept": "*/*", 
          "Authorization": "Bearer HZCdsf=", 
          "Host": "httpbin.org", 
          "Projectname": "zhikovapp", 
          "User-Agent": "curl/7.35.0"
       }, 
       "origin": "1.2.3.4", 
       "url": "http://httpbin.org/get"
    }
    

    requests相同的请求:

    import requests
    res = requests.get('http://httpbin.org/get', headers={
      "projectName"   : "zhikovapp",
      "Authorization" : "Bearer HZCdsf="
    })
    print(res.json())
    
    {
      'args': {},
      'headers': {
         'Accept': '*/*',
         'Accept-Encoding': 'gzip, deflate, compress',
         'Authorization': 'Bearer HZCdsf=',
         'Host': 'httpbin.org',
         'Projectname': 'zhikovapp',
         'User-Agent': 'python-requests/2.2.1 CPython/3.4.3 '
           'Linux/3.16.0-38-generic'
       },
       'origin': '1.2.3.4',
       'url': 'http://httpbin.org/get'
    }
    

    正如您所看到的,唯一的区别是User-Agent头。这不太可能是原因,但您可以很容易地在headers中将其设置为您喜欢的值。

相关问题 更多 >