Python请求卷曲请求

时间:2020-03-01 22:29:48

标签: 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 -X POST --data "test connection" -H '"Content-type": "application/json", "Authorization": "Basic asdfasdf"' dns.com/end

我遇到一个错误: “ status”:404,“ message”:“无可用消息”

1 个答案:

答案 0 :(得分:1)

您有两个问题:

  • 您没有发送JSON数据,却忘记了将数据编码为JSON。将字符串值test connection编码为JSON变为"test connection",但是引号在您的shell中也具有含义,因此您需要添加 extra 引号或转义符
  • 您不能通过单个-H条目设置多个标题。每个标头集使​​用多个。标头不需要引号,只有外壳需要引号以防止参数在空格上分裂。

这等效:

curl -X POST \
  --data '"test connection"' \
  -H 'Content-type: application/json' \
  -H 'Authorization: Basic asdfasdf' \
  dns.com/end

使用https://httpbin.org进行演示:

$ 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"
}