2

我正在尝试使用 requests.post 在 python/django 中进行 RESTful api 调用

我可以让 requests.get(url=url, auth=auth) 工作。该公司在同一个 api 系列中的类似调用

我正在尝试做:

data = {'start': 13388, 'end': 133885, 'name': 'marcus0.5'}
r = requests.post(url=url, auth=auth, headers={'Accept': 'application/json'}, data=data)

我收到以下错误:

>>> r.text
     u'{"status":"error","errorCode":"COMMON_UNSUPPORTED_MEDIA_TYPE","incidentId":"czEtbXNyZXBvcnRzMDQuc3RhZ2V4dHJhbmV0LmFrYW1haS5jb20jMTM3NTgxMzc3MTk4NQ==","errorMessage":"The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.. Content type \'application/x-www-form-urlencoded;charset=UTF-8\' not supported."}'

我认为这与 json 有关,但我不确定是什么,也不知道如何修复它。有任何想法吗?

额外信息[不确定是否适用]:

我进口的

import requests, django

我知道身份验证是正确的,我用 get 方法对其进行了测试

4

1 回答 1

4

您希望将请求的 Content-Type 参数设置为'application/json',而不是 Accept 参数。

取自w3.org

Accept request-header 字段可用于指定响应可接受的某些媒体类型。

试试这个:

import json

data = {'start': 13388, 'end': 133885, 'name': 'marcus0.5'}
r = requests.post(url=url, auth=auth, data=json.dumps(data),
                  headers={'content-type': 'application/json'})

编辑:

dict关于何时将数据作为一个或一个 json 编码的字符串(即 的结果)发送,有一点困惑(对我来说也是如此json.dumps)。这里有一篇很好的文章解释了这个问题。当 API 需要表单编码数据时发送一个简短摘要dict,当它需要 json 编码数据时发送一个 json 编码字符串。

于 2013-08-06T18:48:36.423 回答