2017-10-16 47 views
-1

我正在使用anki-connectAnki(一種間隔重複軟件)進行通信。
在readme.md中,它使用以下命令獲取套牌名稱。如何發佈http請求而不是使用cURL?

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) 
+1

「不幸」是什麼意思?想必你會遇到某種錯誤。什麼是服務器返回? –

+3

[使用Python請求發佈JSON]的可能重複(https://stackoverflow.com/questions/9733638/post-json-using-python-requests) –

+0

您能更詳細地瞭解您所面臨的具體錯誤或問題嗎?你應該能夠找到大量的python提出請求的例子。 – csmckelvey

回答

0

我已經嘗試過下面的挖掘後,這個工程。
任何人都可以分享原因。謝謝。

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) 
1

當創建的請求,你應該:

  • 提供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) 
0

這是對user2444791答案的回覆。我不能評論,因爲我沒有評論的聲譽(我是新的,請原諒一個禮儀的臀位!)

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

查看Anki Connect API,它預計它的POST-ed數據是包含JSON對象的單個字符串,而不是與該JSON對象相同的鍵/值字典。

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

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

這可能是因爲在錯誤的格式發送您的數據一樣簡單。在第一個示例中,您正在發送已經解析了鍵/值對的字典。在第二個例子中,你發送一個字符串讓他們解析。