[英]replicate curl command python 3 urllib request API
這個問題有點使我發瘋。 我正在做一個非常簡單的python 3腳本來管理公共網站中的API。 我可以卷發,但無法在pyhton中使用。 不能在我的真實環境中使用請求庫或curl,僅用於測試
這正在工作:
curl -d "credential_0=XXXX&credential_1=XXXXXX" -c cookiefile.txt https://XXXXXXXXXXXXXXX/LOGIN
curl -d 'json={"devices" : ["00:1A:1E:29:73:B2","00:1A:1E:29:73:B2"]}' -b cookiefile.txt -v https://XXXXXXXXX/api-path --trace-ascii /dev/stdout
我們可以在curl調試中看到這一點:
發送標頭,298字節(0x12a)
0000:POST / api-path HTTP / 1.1
0034:主持人:XXXXXXXXXXXXXXXX
0056:用戶代理:curl / 7.47.0
006f:接受: /
007c:Cookie:csrf_token = 751b6bd9-0290-496b-820e-XXXXXXXX; 會話00bc:= XXXXXX-6d29-4cf9-8907-XXXXXXXXXXXX
00e3:內容長度:60
00f7:內容類型:應用程序/ x-www-form-urlencoded
0128:=>發送數據,60字節(0x3c)
0000:json = {“ devices”:[“ 00:1A:1E:29:73:B2”,“ 00:1A:1E:29:73:B2”]} ==信息:完全發送:60 60字節
這是復制第二個請求的python代碼,這是有問題的
string_query={"devices" : [ "34:FC:B9:CE:14:7E","00:1A:1E:29:73:B2" ]}
jsonbody_url=urllib.parse.urlencode(string_query)
jsonbody_url=jsonbody_url.encode("utf-8")
req=urllib.request.Request(url,data=jsonbody_url,headers={"Cookie" :
cookie,"Content-Type": "application/x-www-form-urlencoded","User-
Agent":"curl/7.47.0","charset":"UTF-8","Content-
length":len(jsonbody_url),
"Connection": "Keep-Alive"},method='POST')
服務器完全忽略了Json內容。 其他所有工作,登錄和來自同一API的其他url參數
有任何想法嗎?
嘗試這個:
import requests
string_query={"devices" : [ "34:FC:B9:CE:14:7E","00:1A:1E:29:73:B2" ]}
headers={
"Cookie" : cookie,
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent":"curl/7.47.0",
"charset":"UTF-8",
"Connection": "Keep-Alive"
}
response = requests.post(url,data=string_query,headers=headers)
print(response.content)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.