簡體   English   中英

如何發布 http 請求而不是使用 cURL?

[英]How can I post http request instead of using cURL?

我正在使用anki-connectAnki進行通信,這是一個間隔重復的軟件。
在 readme.md 中,它使用以下命令獲取卡組名稱。

curl localhost:8765 -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"

它適用於我的 Windows 系統。
如何使用 python 而不是 cURL?
我試過這個,但沒有運氣。

import requests  
r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5})
print(r.text)

創建請求時,您應該:

  • 提供Content-Type標頭
  • 以與Content-Type標頭匹配的格式提供數據
  • 確保應用程序支持該格式

您提供的curlpython示例都使用Content-Type: application/x-www-form-urlencoded發送請求,這是默認的。 區別在於curl傳遞字符串, python傳遞數組。

讓我們比較curlrequests以及真正發布的內容:

卷曲

$ curl localhost -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"

標題:

Host: localhost
User-Agent: curl/7.52.1
Accept: */*
Content-Length: 37
Content-Type: application/x-www-form-urlencoded

發布數據:

[
    '{"action": "deckNames", "version": 5}'
]

Python

import requests  
r = requests.post("http://127.0.0.1", data={'action': 'guiAddCards', 'version': 5})
print(r.text)

標題:

Host: 127.0.0.1
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.10.0
Content-Length: 28
Content-Type: application/x-www-form-urlencoded

發布數據:

[
    'action' -> 'guiAddCards',
    'version' -> '5',
]

如您所見,不正確的帖子數據格式會破壞您的應用程序。

可以肯定的是,應用程序將正確讀取發布的 JSON 數據,您應該發出這樣的請求:

卷曲

$ curl localhost:8765 -H 'Content-Type: application/json' -d '{"action": "deckNames", "version": 5}'

Python

import requests  
r = requests.post("http://127.0.0.1:8765", json={'action': 'guiAddCards', 'version': 5})
print(r.text)

我在挖掘后嘗試過,這有效。
任何人都可以分享原因。 謝謝。

import requests
import json

#r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5})
r = requests.post('http://localhost:8765', data=json.dumps({'action': 'guiAddCards', 'version': 5}))
print(r.text)

這是對 user2444791 的回答的回復。 我無法回復評論,因為我沒有評論的聲譽(我是新人,請原諒禮儀!)

沒有確切的錯誤消息,很難確定,但是......

查看Anki Connect API ,它期望它的 POST-ed 數據是包含 JSON 對象的單個字符串,而不是等效於該 JSON 對象的鍵/值字典。

每個請求都包含一個 JSON 編碼的對象,其中包含一個操作、一個版本和一組上下文參數。

他們的示例代碼(在 Javascript 中): xhr.send(JSON.stringify({action, version, params}));

這可能就像以錯誤的格式發送數據一樣簡單。 在第一個示例中,您正在發送一個已解析鍵/值對的字典。 在第二個示例中,您將發送一個字符串供他們解析。

暫無
暫無

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

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