使用Python在Twitter 1.1中发出仅应用程序的请求

anu*_*agg 5 python twitter http-post oauth-2.0

我想使用仅应用程序身份验证来访问Twitter 1.1搜索端点。为此,我尝试在此处执行Twitter API文档上给出的步骤-https: //dev.twitter.com/docs/auth/application-only-auth (滚动到“发出仅应用程序的请求”)

我无法在步骤2中获得“承载者令牌”。运行以下代码时,我收到“响应:找到302”,这是重定向到位置:https : //api.twitter.com/oauth2/token 理想情况下应为“ 200 OK”

import urllib
import base64
import httplib

CONSUMER_KEY = 'my_key'
CONSUMER_SECRET = 'my_secret'

encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)

concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET

host = 'api.twitter.com'
url = '/oauth2/token'
params = urllib.urlencode({'grant_type' : 'client_credentials'})
req = httplib.HTTP(host)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "gzip")

req.endheaders()
req.send(params)

# get the response
statuscode, statusmessage, header = req.getreply()
print "Response: ", statuscode, statusmessage
print "Headers: ", header
Run Code Online (Sandbox Code Playgroud)

我不想使用任何Twitter API包装器来访问它。

anu*_*agg 3

问题是必须使用 HTTPS 连接来调用 URL。请检查修改后的代码是否有效。

import urllib
import base64
import httplib

CONSUMER_KEY = 'my_key'
CONSUMER_SECRET = 'my_secret'

encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)

concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET

host = 'api.twitter.com'
url = '/oauth2/token/'
params = urllib.urlencode({'grant_type' : 'client_credentials'})
req = httplib.HTTPSConnection(host)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "gzip")

req.endheaders()
req.send(params)

resp = req.getresponse()
print resp.status, resp.reason
Run Code Online (Sandbox Code Playgroud)