Reputation: 43
I am trying to make a http request using requests
library to the redirect url (in response headers-Location). When using Chrome inspection, I can see the response status is 302.
However, in python, requests
always returns a 200 status. I added the allow_redirects=False
, but the status is still always 200.
https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679
[email protected]
112358
and then click the first button to login.
My Python code:
import requests
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36'
session = requests.session()
session.headers['User-Agent'] = user_agent
session.headers['Host'] = 'api.weibo.com'
session.headers['Origin']='https://api.weibo.com'
session.headers['Referer'] ='https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679'
session.headers['Connection']='keep-alive'
data = {
'client_id': api_key,
'redirect_uri': callback_url,
'userId':'[email protected]',
'passwd': '112358',
'switchLogin': '0',
'action': 'login',
'response_type': 'code',
'quick_auth': 'null'
}
resp = session.post(
url='https://api.weibo.com/oauth2/authorize',
data=data,
allow_redirects=False
)
code = resp.url[-32:]
print code
Upvotes: 4
Views: 21046
Reputation: 1124110
You are probably getting an API error message. Use print resp.text
to see what the server tells you is wrong here.
Note that you can always inspect resp.history
to see if there were any redirects; if there were any you'll find a list of response objects.
Do not set the Host
or Connection
headers; leave those to requests
to handle. I doubt the Origin
or Referer
headers here needed either. Since this is an API, the User-Agent
header is probably also overkill.
Upvotes: 8