1

这是一个代码示例:

# 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,它返回有效,所以我不知道为什么服务器会抱怨格式错误。

4

1 回答 1

-3

这不适用于 urllib2,您必须“请求”(http 表示人类):

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)
于 2012-12-12T16:12:32.077 回答