尝试使用urllib2发送JSON有效负载,获取HTTPError 400

时间:2012-12-12 16:01:55

标签: python json urllib2

以下是代码示例:

# 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()

使用错误urllib2.HTTPError: HTTP Error 400: Bad Request调用urlopen失败。我猜我没有正确发送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并且它返回有效,所以我不知道为什么服务器会抱怨格式错误。

1 个答案:

答案 0 :(得分:-3)

这不适用于urllib2,你必须“请求”(http for human):

http://pypi.python.org/pypi/requests

文档提供了用例的示例:http://docs.python-requests.org/en/latest/

我的一个项目的例子:

def query(self, path, **kwargs):
    """the token must be given as GET and args as POST JSON object"""
    encoded_args = urllib.urlencode({"token": self.token})
    url = self.url_tpl % ('/api/%s' % path, encoded_args)
    headers = {'content-type': 'application/json'}

    data = json.dumps(kwargs).encode('utf-8')
    response = requests.post(url, data=data, headers=headers)
    if response.status_code == 200:
        return response.json
    else:
        raise Exception("response status: %s" % response.status_code)