下面是一個代碼示例:嘗試發送JSON有效載荷與urllib2的,越來越HTTPError 400
# Not actual payload, but exact same structure. Verified that payload is correct.
payload = {
'object': {
'token': '6867r474850557',
'contact': {
'FirstName': 'Jim',
'LastName': 'Bob',
'Email': '[email protected]',
'Phone': '111-111-1111'
},
'request': {
'Subject': 'Hello!',
'Message': 'Test Message'
},
'fields': [ "LastName", "FirstName" ]
}
}
r = urllib2.Request("https://someawesomeurl.com", json.dumps(payload), {"Content-type": "application/json"})
f = urllib2.urlopen(r)
resp = f.read()
它無法在電話會議上有錯誤urllib2.HTTPError: HTTP Error 400: Bad Request
到的urlopen。我猜我沒有正確地發送JSON負載,但我不知道我必須做什麼來糾正它。
編輯 這裏的工作PHP實現我想在Python實現:
$url = 'https://someawesomeurl.com';
$body = array (
'object' => array(
'token' => '6867r474850557',
'contact' => array (
'FirstName' => "Jim",
'LastName' => "Bob",
'Email' => "[email protected]",
'Phone' => "111-111-1111"
),
'request' => array (
'Subject' => "Hello!",
'Message' => "Test Message"
),
'fields' => array('LastName')
));
$params = json_encode($body);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_HTTPHEADER, array( "Content-type: application/json"));
$response = curl_exec($curl);
編輯#2難道urllib2
是在發送時它修改JSON?我已經包裹在一個嘗試urlopen
呼叫/ except塊,並打印出來HTTPError's exception message
:
[{"message":"Premature end of list at [line:1, column:727]","errorCode":"JSON_PARSER_ERROR"}]
我已經通過皮棉運行JSON,所以我不知道爲什麼服務器將它回來爲有效抱怨格式不正確。
我建議看看http://stackoverflow.com/questions/3290522/urllib2-and-json –
在該頁面上嘗試了幾個建議。將內容長度添加到頭部並對有效負載進行urlecoding而不是使用json.dumps,這會給我帶來相同的錯誤。 – Don
你是否將請求指向一個有效的域,它可以接受你發送它的數據。你可以在本地主機上設置一些東西來更好地診斷問題。這可能是更多的服務器問題。 –