gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:23:11 26 4
gpt4 key购买 nike

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

我无法在步骤 2 中获得“不记名 token ”。当我运行以下代码时,我收到“响应: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

我不想使用任何 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

关于python - 使用 Python 在 Twitter 1.1 中发出仅应用程序请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15956270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com