我試圖發送post數據並從api(qtortorrent)接收SID以便稍後使用get請求發送。我目前堅持一個OK響應,但json是NULL。這裏是我的代碼:帶有JSON響應的PHP curl POST請求
<?php
$ch = curl_init();
$fields = array('username'=>'Admin','password'=>'mypassword');
$postvars = '';
foreach($fields as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
$postvars = rtrim($postvars, '&');
$url = "https://192.123.123.123:8080/login";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 0);
$headers= array('Accept: application/json','application/x-www-form-urlencoded');
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
var_dump(json_decode($response, true));
print "curl response is:" . $response;
curl_close ($ch);
?>
你可以看到這裏的API載文https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation#authorization
我可以使用PowerShell作爲根本,以獲得JSON:
$prms = @{username="Admin";password="mypassword"}
$res = Invoke-WebRequest https://192.123.123.123:8080/login -Method POST -Body prms -UseBasicParsing
但我不能這樣做所以用PHP!如果你還覺得我的標題權使用SID作爲cookie GET請求,我會比歡迎:)
$ postvars在結尾將會有一個額外的「&」。這是一個問題嗎? ( '用戶名=管理員和密碼=輸入mypassword&')。另外,你是否需要循環來連接字符串,或者你可以發送數組 - curl_setopt($ ch,CURLOPT_POSTFIELDS,$ fields); –
'$ postvars = RTRIM($ postvars,「&');'很可能在這裏需要刪除尾隨符號。 – Ohgodwhy
編輯我的問題,仍然得到同樣的結果。服務器仍然回答‘確定’,我曾與一個錯誤的密碼嘗試我得到「失敗」 – Gab