2012-07-05 84 views
1

我正在製作一個適用於網址的應用程序,我需要縮短它們。我寫了下面的代碼:Google Shortener API和Python錯誤

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'} 

非常感謝您提前。

回答

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/'} 
+0

非常感謝你,現在工作。我雖然發送了Content-Type,但是我的錯。再次感謝。 – aesptux 2012-07-08 19:20:45