我们的API客户端仅支持多部分/form-data和application/x-www-form-urlencoded格式。所以,当我试图访问他们的API:
import requests
import json
url = "http://api.client.com/admin/offer"
headers = {"Content-Type": "multipart/form-data", "API-Key": "ffffffffffffffffffffffffffffffffffffffff"}
data = {"Content-Type": "multipart/form-data", "title": "Demo offer", "advertiser": "f4a89a7h1aq", "url": "http://demo.com/", "url_preview": "http://demo.com/", "description": "Bla bla bla", "freshness": "fresh", "total": "2.0", "revenue": "1.8"}
r = requests.post(url, headers=headers, data=json.dumps(data))
print r.text
我得到这个:
{"status":2,"error":"Submitted wrong data. Check Content-Type header"}
如何克服这个问题?
谢谢!
我们的API客户仅支持多部分/表单数据和application/x-www-form-urlencoded format
然而,您将Content-type
标头设置为application/json
,而不是multipart/form-data
或application/x-www-form-urlencoded
。
在HTTP请求的正文中设置内容类型将没有帮助。
服务器似乎不支持JSON。您应该尝试将数据作为标准表单发布,如下所示:
import requests
import json
url = "http://api.client.com/admin/offer"
headers = {"API-Key": "ffffffffffffffffffffffffffffffffffffffff"}
data = {"title": "Demo offer", "advertiser": "f4a89a7h1aq", "url": "http://demo.com/", "url_preview": "http://demo.com/", "description": "Bla bla bla", "freshness": "fresh", "total": "2.0", "revenue": "1.8"}
r = requests.post(url, headers=headers, data=data)
print r.text
默认情况下,requests.post
会将内容类型标头设置为application/x-www-form-urlencoded
,并对请求正文中的数据进行"urlencode"。这应该是有效的,因为您声明服务器支持application/x-www-form-urlencoded
。