问题描述
我必须使用Python发出HTTPS请求,并且我正在使用请求模块来尝试简化我的生活.
I have to make an HTTPS request in Python, and I am using the requests module to try to make my life easier.
该请求需要具有标头和3个FORM参数URL编码.这就是我正在做的:
The request needs to have a header and 3 FORM parameters URL encoded. This is what I am doing:
header = {'Content-type': 'application/x-www-form-urlencoded', 'Authorization':'Basic ' + encoded_string, 'Connection': 'Keep-Alive', 'Host':'host.host.com'}
payload='grant_type=authorization_code&code=' + request.args['code'] + '&state=' + request.args['state'] + '&redirect_uri=http://xxx.xyz.com/request_listener'
url = 'https://serviceprovider.xxx.com/auth/j_oauth_resolve_access_code'
response = requests.post(url, data=payload, headers=header, verify=False)
当我尝试返回 response
的 content
或 text
时,我得到一个空字符串.但是,当我打印实际的 response
对象时,它表示它是< Response [200]>
,但是如果实际上是200 OK,则服务器我在发布时也应该转到我指定的redirect_uri,我会在那里收到通知.
When I try to return the content
or text
of the response
, I get an empty string. However, when I print the actual response
object, it says it is a <Response [200]>
, but if this were actually a 200 OK then the server I am POSTing too should go to the redirect_uri I have specified and I would get a notification there.
这没有发生,我对原因感到迷茫.
This is not happening, and I am mystified as to why.
推荐答案
您的代码正在与Requests库对抗:您自己在做很多事情,Requests会为您做这些事情.
Your code is fighting the Requests library: you're doing a lot of stuff yourself that Requests will do for you.
首先,不要自己对数据进行格式编码,而让Requests通过提供一个指向 data
的字典来完成它,就像@flyer的建议答案一样.
Firstly, don't form-encode your data yourself, let Requests do it by providing a dictionary to data
, like @flyer's answer suggested.
执行此操作时,请求还将正确设置Content-Type标头,因此您不必这样做.另外,请不要发送 Connection
标头:请求将为您管理.同样适用于 Host
标头:发送 Host
标头只会导致问题.
When you do this, Requests will also correctly set the Content-Type header, so you don't have to. Also, please don't send a Connection
header: Requests will manage it for you. The same applies to Host
headers: sending a Host
header can only cause problems.
最后,不要自己设置Authorization标头,而让Requests通过为其提供身份验证凭据来完成.惯用的请求代码为:
Finally, don't set the Authorization header yourself, let Requests do it by providing it with your authentication credentials. The idiomatic Requests code would be:
payload = {
'grant_type': 'authorization_code',
'code': request.args['code'],
'state': request.args['state'],
'redirect_uri': 'http://xxx.xyz.com/request_listener',
}
url = 'https://serviceprovider.xxx.com/auth/j_oauth_resolve_access_code'
response = requests.post(url, data=payload, verify=False)
如果这不起作用,那么我怀疑您的有效载荷数据不正确.
If that doesn't work, then I would suspect your payload data is bad.
这篇关于使用请求模块发出Python HTTPS请求的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!