aes*_*tux 1 python api json google-url-shortener
我正在制作一个与网址一起使用的应用程序,我需要缩短它们.我写了以下代码:
import requests, json
gUrl = 'https://www.googleapis.com/urlshortener/v1/url'
data = json.dumps({'longUrl': 'http://www.google.es'})
r = requests.post(gUrl, data)
Run Code Online (Sandbox Code Playgroud)
它应该用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'}]}}
Run Code Online (Sandbox Code Playgroud)
其他可能有用的信息:
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'}
Run Code Online (Sandbox Code Playgroud)
非常感谢你提前.
您需要确保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/'}
Run Code Online (Sandbox Code Playgroud)