(我知道标题中有很多请求)
通过 Fiddler,我收到了一个请求。它正是我想要的。当我尝试用 python 重现它时,它不起作用。这是 Fiddler 请求:
POST https://ichthus.zportal.nl/api/v3/oauth/ HTTP/1.1
Host: ichthus.zportal.nl
Content-Type: application/x-www-form-urlencoded
username=138777&password=XXXXX&client_id=OAuthPage&redirect_uri=%2Fmain%2F&scope=&state=4E252A&response_type=code&tenant=ichthus
这是我尝试过的 Python 请求代码:
import requests
endpoint = "https://ichthus.zportal.nl/api/v3/oauth/"
authData = {
'username': '138777',
'password': 'XXXXX',
'client_id': 'OAuthPage',
'redirect_uri': '/main/',
'scope': '',
'state': '4E252A',
'response_type': 'code',
'tenant': 'ichthus',
}
header = {
'Host': 'ichthus.zportal.nl',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.post(endpoint, data=authData, headers=header)
print response.headers
print response.status_code
与 Request to Code我设法将其发送给 python URLlib2 请求。但我以前从未使用过 URLlib,我想知道是否可以将其转换为 Python Requests 请求。这是 Python URLlib2 代码:
def make_requests():
response = [None]
responseText = None
if(request_ichthus_zportal_nl(response)):
responseText = read_response(response[0])
response[0].close()
def request_ichthus_zportal_nl(response):
response[0] = None
try:
req = urllib2.Request("https://ichthus.zportal.nl/api/v3/oauth/")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
body = "username=138777&password=XXXX&client_id=OAuthPage&redirect_uri=%2Fmain%2F&scope=&state=4E252A&response_type=code&tenant=ichthus"
response[0] = urllib2.urlopen(req, body)
except urllib2.URLError, e:
if not hasattr(e, "code"):
return False
response[0] = e
except:
return False
return True
最佳答案
Requests 是一个非常流行的外部库,但我不建议依赖它。
我确实注意到您在请求中发送了以下“数据”
authData = {
'username': '138777',
'password': 'XXXXX',
'client_id': 'OAuthPage',
'redirect_uri': '/main/',
'scope': '',
'state': '4E252A',
'response_type': 'code',
'tenant': 'ichthus',
}
但是您指定数据类型为 'Content-Type': 'application/x-www-form-urlencoded'
并且您从未对数据进行编码。这也可能是你的罪魁祸首。
此外。 Requests 只是 urllib2 的一个包装器,可以自动完成很多工作。
尝试将其与 urllib/2 一起使用
Urllib2.urlopen (url, data)
数据使用
进行 url 编码Urllib.urlencode ()
有关更多详细信息,请参阅 python 文档。
关于python - Fiddler 请求到 Python Requests 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994083/