我必须在 Python 中发出 HTTPS 请求,我正在使用请求模块来尝试让我的生活更轻松。
请求需要有一个 header 和 3 个 FORM 参数 URL 编码。这就是我正在做的:
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)
当我尝试返回 content
时或 text
的 response
,我得到一个空字符串。但是,当我打印实际的 response
时对象,它说它是一个 <Response [200]>
,但如果这实际上是 200 OK,那么我正在发布的服务器也应该转到我指定的 redirect_uri,我会在那里收到通知。
这并没有发生,我不明白为什么。
最佳答案
您的代码正在与 Requests 库作斗争:您正在自己做很多 Requests 会为您做的事情。
首先,不要自己对数据进行形式编码,让 Requests 通过向 data
提供字典来完成,就像@flyer 的建议回答一样。
当您执行此操作时,Requests 还将正确设置 Content-Type header ,因此您不必这样做。另外,请不要发送 Connection
header :Requests 将为您管理它。这同样适用于 Host
header :发送 Host
header 只会导致问题。
最后,不要自己设置 Authorization header ,让 Requests 通过提供您的身份验证凭据来完成。惯用的请求代码是:
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)
如果这不起作用,那么我会怀疑您的有效负载数据有问题。
关于python - 使用请求模块发出 Python HTTPS 请求的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20485772/