简体   繁体   English

Python 请求 HTTP 响应 406

[英]Python Requests HTTP Response 406

I have my own domain where an json file is stored ( http://example.com/file.json) .我有自己的域,其中存储了 json 文件 ( http://example.com/file.json) When accesing the file in browser using the direct link, the json is returned just fine.使用直接链接访问浏览器中的文件时,返回 json 就好了。 But when using the same approach in my python code below, the http response is 406 .但是当在下面的 python 代码中使用相同的方法时,http 响应是406 Any ideas why?任何想法为什么?

import requests
url = 'http://example.com/file.json'
r = requests.get(url, headers={"Accept":"text/html"})
print(r.status_code)
print(r.headers)

Prints:印刷:

406
{'Server': 'nginx/1.14.1', 'Date': 'Sun, 12 May 2019 16:53:25 GMT', 'Content-Type': 'text/html; charset=iso-8859-1', 'Content-Length': '226', 'Connection': 'k
eep-alive'}

Solved by using a different User-Agent.通过使用不同的用户代理解决。 The default Python User-Agent 'python-requests/2.21.0' was being probably blocked by the hosting company.默认的 Python 用户代理'python-requests/2.21.0'可能被托管公司阻止。

r = requests.get(url, headers={"User-Agent": "XY"})

Some of the possible agents: List of User Agent strings一些可能的代理:用户代理字符串列表

Your own accepted answer is most likely incorrect.您自己接受的答案很可能是不正确的。 This error means the value of Accept header does not match Content-Type of the response.此错误意味着Accept标头的值与响应的Content-Type不匹配。 If you'd send Accept: */* , it would work (at least the 406 would not be returned).如果您发送Accept: */* ,它将起作用(至少不会返回406 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM