这是一个代码示例:
# Not actual payload, but exact same structure. Verified that payload is correct.
payload = {
'object': {
'token': '6867r474850557',
'contact': {
'FirstName': 'Jim',
'LastName': 'Bob',
'Email': 'email@fmail.com',
'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()
调用 urlopen 失败并显示错误urllib2.HTTPError: HTTP Error 400: Bad Request
。我猜我没有正确发送 JSON 有效负载,但我不确定我必须做些什么来纠正它。
编辑 这是我试图在 Python 中实现的有效 PHP 实现:
$url = 'https://someawesomeurl.com';
$body = array (
'object' => array(
'token' => '6867r474850557',
'contact' => array (
'FirstName' => "Jim",
'LastName' => "Bob",
'Email' => "email@fmail.com",
'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
调用包装在 try/except 块中并打印出来HTTPError's exception message
:
[{"message":"Premature end of list at [line:1, column:727]","errorCode":"JSON_PARSER_ERROR"}]
我已经通过 lint 运行了 JSON,它返回有效,所以我不知道为什么服务器会抱怨格式错误。