2

有人可以解释为什么它不转换为jsonfromtext以及我需要什么来完成它以及如何完成它。

>>> import json
>>> import requests
>>> url = 'http://localhost:8000/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
>>> r.headers.get('content-type')
'text/html'
>>>

更新:

将标头接受为 application/json 导致我无法解码任何 JSON 对象。请帮忙..

>>> import json
>>> import requests
>>> url = 'http://localhost:8000/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json','accept':'application/json'}  
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
>>> r.headers
CaseInsensitiveDict({'date': 'Thu, 13 Jun 2013 01:43:16 GMT', 'content-type':         'text/html', 'server': 'WSGIServer/0.1 Python/2.7.3'})
>>> r.json()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/models.py",      line 651, in json
return json.loads(self.text or self.content, **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
 return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>>
4

1 回答 1

2

您只是说明您的请求的内容类型是application/json. 您可以尝试使用accept-header请求 json :

headers["Accept"] = "application/json"

但如果服务器忽略标头,它将无济于事。

此外,响应内容实际上可能是 json,因此r.json()可能会起作用,而且只有 content-type 标头具有误导性。

于 2013-06-12T19:25:08.137 回答