我正在尝试使用python请求库通过API授权bitly。
我使用http://hottr.tk/ NSFW作为我的回调url。而且它被设置在一些小设置中。
from lxml import html
from urllib import parse
import requests
# BASIC INITIALIZATION
username = 'username@fixme.org'
password = 'fixmetoo'
client_id = '18c1065bb7e3cfea7fa80d2c30ee974c6a9c4dba'
# CREATE REQUESTS SESSION
r = requests.session()
# LOGIN TO BITLY
response = r.get("https://bitly.com/a/sign_in")
s = html.fromstring(response.text)
_xsrf = s.xpath("//input[@name='_xsrf']")[0].value
r.headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-XSRFToken': _xsrf,
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
}
payload = {
'username': username,
'password': password,
'rd': '/',
'_xsrf': _xsrf,
'verificaton': 'true',
}
cookie = requests.utils.dict_from_cookiejar(r.cookies)
response = r.post("https://bitly.com/a/sign_in", headers=r.headers, data=payload, cookies=cookie)
# GET to REQUEST AUTHORIZE ENDPOINT
response = r.get("https://bitly.com/oauth/authorize?client_id=" + client_id + "&redirect_uri=" + parse.quote_plus('http://hottr.tk/'))
# POST to REQUEST AUTHORIZE ENDPOINT
r.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'es',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
# 'Content-Length': '147',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'bitly.com',
'Origin': 'https://bitly.com',
'Referer': 'https://bitly.com/oauth/authorize?client_id=" + client_id + "&redirect_uri=http://hottr.tk/',
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
}
payload = {
'_xsrf': _xsrf,
'redirect_uri': parse.quote_plus('http://hottr.tk/'),
'client_id': client_id,
'state': '',
'action': 'Allow',
}
cookie = requests.utils.dict_from_cookiejar(r.cookies)
response = r.post("https://bitly.com/oauth/authorize", headers=r.headers, data=payload, cookies=cookie)
print(response.headers)
print(response.url)在这一点上,最后的POST请求应该授权应用程序,并与http://hottr.tk/?code=my_code_to_exchange_for_oauth_token和url一起返回,但它只返回response.url --这个https://bitly.com/,并且它没有response.headers.location变量,这是一个变量,它应该用code参数来保存重定向url。
身份代码都是200..。
有人知道它为什么返回到https://bitly.com而不是我的重定向url?:$
发布于 2015-10-27 08:13:55
哈哈,我想了个更好的办法。这里有很好的文档记录:credentials
import base64
username = b'fixme'
password = b'fixmetoo'
r = requests.session()
r.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'api-ssl.bitly.com',
'Authorization': 'Basic ' + base64.b64encode(username + b':' + password).decode('utf-8'),
}
response = r.post("https://api-ssl.bitly.com/oauth/access_token", headers=r.headers)
print(response.content.decode('utf-8'))https://stackoverflow.com/questions/33362029
复制相似问题