从curl转换为python www.example.com时出现意外响应request.post

mdfafbf1  于 2022-11-13  发布在  Python
关注(0)|答案(1)|浏览(108)

我正在尝试在Python3.8中实现一个有效的curl调用。

curl -H application/x-www-form-urlencoded --silent -d "client_id=bob&client_secret=djfheucnjdi54ndjdjddkdjs&grant_type=password&scope=openid email profile&username=user1&password=password" -X POST https://some.okta.com/auth/api/v1/token

上面的curl调用(敏感数据修改)成功,返回一个json:

{
    "token_type": "Bearer",
    "expires_in": 3600,
    "access_token": "**********************************************************************",
    "scope": "openid profile email",
    "id_token": "**********************************************************************"
}

我试过把这个转换成Python,然后用在线curl验证转换成Python,但是没有得到预期的结果。
Python代码:

import requests

okta_headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
}

okta_parameters = 'client_id=bob&client_secret=djfheucnjdi54ndjdjddkdjs&grant_type=password&scope=openid email profile&username=user1&password=password'

response = requests.post('https://some.okta.com/auth/api/v1/token', headers=okta_headers, data=okta_parameters)
print(response.content)

但是得到了如下输出,看起来像是页面的源代码(?):

b'<!DOCTYPE html>\n<!--[if IE 7]><html lang="en" class="lt-ie10 lt-ie9 lt-ie8"><![endif]-->\n<!--[if IE 8]><html lang="en" class="lt-ie10 lt-ie9"> <![endif]-->\n<!--...

你知道为什么和/或如何从最初的curl调用中得到那个json吗?
谢谢你的帮助。

2lpgd968

2lpgd9681#

更新

嗯...我直接从www.example.com复制了输出formatter.xyz/curl-to-python-converter只是为了确保我没有做任何愚蠢的事情。
所以你不能查看请求的头吗?如果不能,你能改变网址,到你自己的服务器上去看看头吗?你真的需要查看头。
Curl通常有一个配置或上下文,它有默认的头文件。这两个rev可能有不同的默认值。除了在curl选项中覆盖的值之外,都使用了错误。
每当我发出curl请求时,我都会提供大多数请求参数。
这是我的标准请求头(PHP)。

$request = array();
$request[] = "Host: www.example.com";
$request[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$request[] = "User-Agent: MOT-V9mm/00.62 UP.Browser/6.2.3.4.c.1.123 (GUI) MMP/2.0";
$request[] = "Accept-Language: en-US,en;q=0.5";
$request[] = "Connection: keep-alive";
$request[] = "Cache-Control: no-cache";
$request[] = "Pragma: no-cache";

更新结束

两者之间必须有两个不同的请求标头。
如果您在请求中犯了最小的错误/打字错误,它可能会对响应产生重大影响。
如果curl提供了捕获传出请求头的方法/选项,请比较两者。
如果没有,您需要仔细检查请求标题的每个细节,并找到错字。
同时确保没有304重定向。一个重定向可以在两个不同的curl函数之间改变事情。

相关问题