2016-08-03 13 views
-1

我們的API客戶端僅支持multipart/form-data和application/x-www-form-urlencoded格式。所以,當我試圖訪問其API:如何在python中使用requests模塊進行multipart/form-data或application/x-www-form-urlencoded請求?

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"} 

如何解決這個問題?

謝謝!

回答

2

我們的API客戶端僅支持多/表單數據和 應用程序/ x-WWW-form-urlencoded格式

然而,你正在設置Content-typeapplication/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將Content-type頭設置爲application/x-www-form-urlencoded並將「進行urlencode」中的數據請求的主體。這應該工作,因爲你聲明服務器支持application/x-www-form-urlencoded

+0

謝謝你,你已經注意到我沒有從我的代碼中刪除json.dumps()。問題在於:-) – paus

相關問題