在Twitter1.1中使用Python发出仅应用程序请求

在Twitter1.1中使用Python发出仅应用程序请求,python,twitter,oauth-2.0,http-post,Python,Twitter,Oauth 2.0,Http Post,我想使用仅应用程序身份验证访问Twitter 1.1搜索端点。为了实现同样的目的,我正在尝试实现Twitter API文档中给出的步骤(滚动到“仅发布应用程序请求”) 我无法在步骤2中获得“持票人代币”。当我运行以下代码时,我收到“Response:302 Found”,这是指向位置的重定向: 理想情况下,它应该是“200 OK” 我不想使用任何Twitter API包装来访问此内容。问题是必须使用HTTPS连接调用URL。请检查修改后的代码是否有效 import urllib import b

我想使用仅应用程序身份验证访问Twitter 1.1搜索端点。为了实现同样的目的,我正在尝试实现Twitter API文档中给出的步骤(滚动到“仅发布应用程序请求”)

我无法在步骤2中获得“持票人代币”。当我运行以下代码时,我收到“Response:302 Found”,这是指向位置的重定向: 理想情况下,它应该是“200 OK”


我不想使用任何Twitter API包装来访问此内容。

问题是必须使用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

虽然这有点晚了,但您可能会在github页面上找到一些帮助。我已经开始为twitter应用程序特有的身份验证方法创建一个库


HTTP302
是一个重定向。检查
位置:
并重定向?@ch3ka位置正确。它显示“location:”如果遵循重定向(请求location:field中的URL),会发生什么?顺便说一句,“302”回答不是一个错误,而是像ch3ka所说的重定向。@CaptSolo谢谢,我编辑了这个问题。但是,位置中的URL指向,我的URL与参数相同,即host='api.twitter.com',URL='/oauth2/token'这与https有关吗?@anu.agg它可能与https有关(与https有关)。文件说,进行身份验证时必须使用HTTPS(否则任何人都可能窃取您的密钥)。也许他们通过使用重定向来强制执行它。
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