簡體   English   中英

Python請求卷曲請求

[英]Python request to curl request

發送示例消息的示例 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

使用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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM