我正在制作一个使用 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'}
非常感谢您。
请您参考如下方法:
您需要确保 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/'}
