【问题标题】:Translating Python HTTP request to curl将 Python HTTP 请求转换为 curl
【发布时间】:2019-08-17 10:09:32
【问题描述】:

我在 Python 中有以下代码,它正在对 OAuth2 令牌发出 POST 请求。它使用基本身份验证。 代码运行良好,但我想将其“翻译”为 curl。

代码:

#Authorization: Basic c29tZV91c2VyOnBhc3M=
#some_user:pass = base64decode('c29tZV91c2VyOnBhc3M=') 

def get_access_token():
burp0_url = "https://myurl:443/api/oauth/token"
burp0_headers = {"Accept": "application/json", "Authorization": "Basic c29tZV91c2VyOnBhc3M=", "Content-Type": "application/x-www-form-urlencoded", "Connection": "close", "Accept-Encoding": "gzip, deflate", "User-Agent": "okhttp/3.0.1"}
burp0_data={"grant_type": "client_credentials"}
return json.loads(requests.post(burp0_url, headers=burp0_headers,
data=burp0_data).text)['access_token']

我的猜测是它看起来像这样:

curl -v -XPOST -H 'Authorization: Basic c29tZV91c2VyOnBhc3M=' --header 'Accept: application/json' --header 'Connection: close' --header 'Accept-Encoding: gzip, deflate' --header 'User-Agent: okhttp/3.0.1' --data '{"grant_type": "client_credentials"}' https://myurl:443/api/oauth/token

但是我不断收到 HTTP/1.1 400 及以下
* 书写体失败 (0 != 10)
* 写入数据失败
* 停止暂停流!
* 关闭连接 0

你能帮帮我吗?

【问题讨论】:

    标签: python json http curl request


    【解决方案1】:

    您好像忘记将 "Content-Type": "application/x-www-form-urlencoded" 标头复制到您的 curl 命令中。

    这也表明数据不是像您目前所做的那样作为 JSON 字符串提交,而是作为常规表单数据提交。您可能可以为此使用 -F 'grant_type=client_credentials' 并删除 --data 参数。

    【讨论】:

    • 我不确定 -F 选项是否要求 Content-Type 为“multipart”。我将请求更改为 curl -v -XPOST -H 'Authorization: Basic c29tZV91c2VyOnBhc3M=' --header "Content-Type: multipart/form-data" --header 'Accept: application/json' --header 'Connection: close' --header 'Accept-Encoding: gzip, deflate' --header 'User-Agent: okhttp/3.0.1' --form "grant_type=client_credentials" https://myurl:443/api/oauth/token我现在得到 200,但仍然得到 * Failed writing body (0 != 10) * Failed writing data * Closing connection 0 - 谢谢,不过
    • 您是否将结果传送到任何地方?快速的 Google 搜索似乎表明该错误意味着 curl 收到了 10 个字节,但只能将 0 个字节写入请求的输出目标 (-o)。由于您没有提供 -o 参数,我想知道您是否将输出发送到了您不期望的地方,或者您没有写入权限。
    • 另见this question on AskUbuntu,它有类似的错误输出
    • 我也尝试使用 -o。它会创建一个带有乱码的文件。 ? ?î- -0??¦E÷_ǦmL¶gB¦>%¶¦Éõð"¦+íÎaf¥4½óÍðÂ?+=h¶w}-¦y=Þ¦$6 之类的东西 - 可能是由于终端使用的编码(我使用的是 Windows)
    • 这看起来像 gzip 压缩的数据,正是您的 Accept-Encoding 标头所要求的。你应该可以通过adding --compressed to the command 让 curl 自动解压
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2020-03-18
    相关资源
    最近更新 更多