我在下面的卷曲中有这个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'
我正在使用python 2.7
编辑:在Soviut指出它们之后,我纠正了一些syntex错误。答案 0 :(得分:15)
在request.get()
中,headers
参数应定义为字典,一组键/值对。您已经定义了一组字符串(唯一列表)。
您应该像这样声明标题:
headers = {
"projectName": "zhikovapp",
"Authorization": "Bearer HZCdsf="
}
response = requests.get(bl_url, headers=headers)
请注意字典中每行的"key": "value"
格式。
修改:您的Access-Control-Allow-Headers
表示他们会以小写字母接受projectname
和authorization
。您已将标题projectName
和Authorization
命名为大写字母。如果他们不匹配,他们将被拒绝。
答案 1 :(得分:1)
$today
,则可以拨打curl
来电,并且您不能替换requests
&#39;调用网址,然后它可能是 400错误请求的原因。Access-Control-*
和其他CORS标头与非浏览器客户端无关。 HTTP标头通常也不区分大小写。按照@ 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
。