如何使用 python 中的请求模块处理 multipart/form-data 或 application/x-www-form-urlencoded 请求?

How to proceed multipart/form-data or application/x-www-form-urlencoded request using requests module in python?

我们的 API 客户端仅支持 multipart/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"}

如何解决这个问题?

谢谢!

Our API clients support only multipart/form-data and application/x-www-form-urlencoded format

然而你将 Content-type header 设置为 application/json,这不是 multipart/form-data 也不是 application/x-www-form-urlencoded.

在 HTTP 请求的 body 中设置内容类型没有帮助。

服务器似乎不支持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 会将 Content-type header 设置为 application/x-www-form-urlencoded 并将 "urlencode" 请求的 body 中的数据.这应该有效,因为您声明服务器支持 application/x-www-form-urlencoded.