1

我正在制作一个适用于 url 的应用程序,我需要缩短它们。我写了以下代码:

import requests, json
gUrl = 'https://www.googleapis.com/urlshortener/v1/url'
data = json.dumps({'longUrl': 'http://www.google.es'})
r = requests.post(gUrl, data)

它应该用 json 编码,但是,我收到以下错误:

print r.json
{u'error': {u'code': 400, u'message': u'This API does not support parsing form-encoded
input.', u'errors': [{u'domain': u'global', u'message': u'This API does not support
parsing form-encoded input.', u'reason': u'parseError'}]}}

其他可能有用的信息:

print r.request
Request [POST]


print r.headers
{'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff',
'transfer-encoding': 'chunked', 'expires': 'Thu, 05 Jul 2012 20:47:11 GMT',
'server': 'GSE', 'cache-control': 'private, max-age=0', 
'date': 'Thu, 05 Jul 2012 20:47:11 GMT', 'x-frame-options': 'SAMEORIGIN', 
'content-type': 'application/json; charset=UTF-8'}

非常感谢您提前。

4

1 回答 1

8

您需要确保Content-Type: application/json正在发送,否则 POST 数据是表单编码的。

例如 r = requests.post(gUrl, data, headers={'Content-Type': 'application/json'}

print r.json- 输出:

{u'kind': u'urlshortener#url', u'id': u'http://goo.gl/5Af0', u'longUrl': u'http://www.google.es/'}
于 2012-07-05T21:47:10.553 回答