PHP curl POST请求与JSON响应

时间:2016-02-27 20:37:00

标签: php json post curl get

我正在尝试发送帖子数据并从api(qbittorrent)接收SID,以便稍后发送获取请求。我目前坚持OK响应,但json为NULL。这是我的代码:

<?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来获取请求,我将非常欢迎:)

1 个答案:

答案 0 :(得分:0)

问题出在那里,改变了:

curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_HEADER, true);

我得到了我的json回复!