Python请求到curl请求

Python请求到curl请求,python,curl,python-requests,Python,Curl,Python Requests,发送示例消息的示例python代码 import requests url = "dns.com/end" msg = "test connection" headers = {"Content-type": "application/json", "Authorization": "Basic asdfasdf"} requests.post(url, json=msg, headers=headers) 现在,我想使用curl请求发送完全相同的消息 curl -

发送示例消息的示例python代码

import requests

url = "dns.com/end"
msg = "test connection"
headers = {"Content-type": "application/json",
            "Authorization": "Basic asdfasdf"}

requests.post(url, json=msg, headers=headers)
现在,我想使用curl请求发送完全相同的消息

curl -X POST --data "test connection" -H '"Content-type": "application/json", "Authorization": "Basic asdfasdf"' dns.com/end
我得到一个错误: “状态”:404,“消息”:“没有可用消息”

您有两个问题:

  • 您没有发送JSON数据,您忘记了将数据编码为JSON。将字符串值
    test connection
    编码为JSON将成为
    “test connection”
    ,但是引号在shell中也有意义,因此需要添加额外的引号或转义符
  • 不能用一个
    -H
    条目设置多个标题。使用多个,每个标题集一个。头不需要引号,只有shell需要引号来防止参数在空格上分裂
这相当于:

curl-X POST\
--数据“测试连接”\
-H'内容类型:应用程序/json'\
-H“授权:基本asdfasdf”\
dns.com/end
演示使用:

$curl-X POST\
>--数据“测试连接”\
>-H“内容类型:应用程序/json”\
>-H“授权:基本asdfasdf”\
>   https://httpbin.org/post
{
“args”:{},
“数据”:“测试连接”,
“文件”:{},
“形式”:{},
“标题”:{
“接受”:“*/*”,
“授权”:“基本asdfasdf”,
“内容长度”:“17”,
“内容类型”:“应用程序/json”,
“主机”:“httpbin.org”,
“用户代理”:“curl/7.54.0”,
“X-Amzn-Trace-Id”:“根=1-5e5c399c-201cc8007165873084d4cf38”
},
“json”:“测试连接”,
“来源”:“,
“url”:”https://httpbin.org/post"
}
与Python等效项匹配的:

导入请求 >>>url='1〕https://httpbin.org/post' >>>msg=“测试连接” >>>标题={“内容类型”:“应用程序/json”, …“授权”:“基本asdfasdf”} >>>response=requests.post(url,json=msg,headers=headers) >>>打印(response.text) { “args”:{}, “数据”:“测试连接”, “文件”:{}, “形式”:{}, “标题”:{ “接受”:“*/*”, “接受编码”:“gzip,deflate”, “授权”:“基本asdfasdf”, “内容长度”:“17”, “内容类型”:“应用程序/json”, “主机”:“httpbin.org”, “用户代理”:“python请求/2.22.0”, “X-Amzn-Trace-Id”:“根=1-5e5c3a25-50c9db19a78512606a42b6ec” }, “json”:“测试连接”, “来源”:“, “url”:”https://httpbin.org/post" }
使用Python代码会得到什么结果?