1

URL で動作するアプリを作成しており、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 に答える