1
我試圖使用application-only authentication來製作Twitter API請求,但發送HTTP請求以接收持票人令牌時發生403錯誤。我認爲這可能是由於我的要求沒有正確形成,但我找不到錯誤(遵循上面的指導原則)。嘗試使用Twitter API驗證應用程序時出現403錯誤
我的代碼(Python的3.5)如下:
btwitter = twitterkey.encode('utf-8') #utf-8 encodes the key
twitterkey = b64encode(btwitter) #b64 encode key from "consumer:secret" to bytes
twitterkey = bytes.decode(twitterkey) # decodes to string
url = "https://api.twitter.com/oauth2/token"
data = "grant_type=client_credentials"
data = data.encode('utf-8')
headers = {'Authorization' : "Basic "+twitterkey+"", 'Content-Length' : '29','User-Agent':'myapp v1','Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}
method = 'POST'
request = urllib.request.Request(url,data,headers,method)
response = urllib.request.urlopen(request)
我也不能肯定,如果我正確編碼的關鍵。按照Twitter的文檔,我將字符串編碼爲字節,然後base64。然後,我將base64轉換回字符串,以便將它連接到「Basic」,否則我會得到TypeError。
運行此代碼,我得到最後一行的錯誤,如下圖所示:
File "main.py", line 69, in <module>
response = urllib.request.urlopen(request)
...
File "<path>", line 589, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
編輯:
捕獲錯誤並打印後,我得到如下:
b'{"errors":[{"code":99,"message":"Unable to verify your credentials","label":"authenticity_token_error"}]}'
我試過更改標題(添加/刪除內容長度和用戶代理),但我得到相同的錯誤。謝謝。
看到錯誤響應的主體是什麼樣子會很有趣。我想我對這裏發生的事情有一個想法,但我想先確定一下。 – DaSourcerer
我添加了error.fp.read()的輸出,但我不知道該怎麼做 –