python - 使用请求模块发出 Python HTTPS 请求的正确方法?

标签 python https python-requests

我必须在 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 时或 textresponse ,我得到一个空字符串。但是,当我打印实际的 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/

相关文章:

javascript - 为什么在尝试更改链接属性时,即使控制台输出正确的结果,DOM 仍保持不变?

node.js - 设置 Node 服务器(https)

python - 在 Python 中根据请求发送 PIL 图像

带有请求的 Python post cookie

python - 将打印作业从python发送到谷歌云打印

python - 80端口上的Django项目?

Python ctypes 无法在结构中传递内存数组

python - cx_Freeze : no base named Console

python - 在 mechanize 中提交表单

当代理服务器用于 LAN 时的 PowerShell Remoting