python - python请求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 \
--data '"test connection"' \
-H 'Content-type: application/json' \
-H 'Authorization: Basic asdfasdf' \
dns.com/end
$ curl -X POST \
> --data '"test connection"' \
> -H 'Content-type: application/json' \
> -H 'Authorization: Basic asdfasdf' \
> https://httpbin.org/post
{
"args": {},
"data": "\"test connection\"",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Authorization": "Basic asdfasdf",
"Content-Length": "17",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/7.54.0",
"X-Amzn-Trace-Id": "Root=1-5e5c399c-201cc8007165873084d4cf38"
},
"json": "test connection",
"origin": "<ip address>",
"url": "https://httpbin.org/post"
}
与 Python 等效项匹配:
>>> import requests
>>> url = 'https://httpbin.org/post'
>>> msg = "test connection"
>>> headers = {"Content-type": "application/json",
... "Authorization": "Basic asdfasdf"}
>>> response = requests.post(url, json=msg, headers=headers)
>>> print(response.text)
{
"args": {},
"data": "\"test connection\"",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Basic asdfasdf",
"Content-Length": "17",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5e5c3a25-50c9db19a78512606a42b6ec"
},
"json": "test connection",
"origin": "<ip address>",
"url": "https://httpbin.org/post"
}
推荐阅读
- r - 在 R 中,如何匹配来自 2 个不同列的值的前 3 个字符
- css - 如何覆盖外部 CSS?
- php - PHP mysqli_fetch_all 将总行数和数据放在一起
- ms-word - 在 MS Word 插件中使用 OfficeJS API 将文本标记为“隐藏”
- r - R中的标准化数据表
- javascript - 从云函数中的数据获取数组(“TypeError:data.filters.forEach 不是函数”)
- javascript - VSCode 如何加载 .js.map 来查看/编辑 js 文件?
- r - 如何使用一列和另一列的平均值绘制折线图?
- c++ - 在 C++ 中,如何在更改第一个参数时包装 Variadic 函数
- python - pyaudio 每次我尝试安装时都会给我一个错误