【问题标题】:PHP curl POST request with JSON response带有 JSON 响应的 PHP curl POST 请求
【发布时间】:2016-06-11 01:14:38
【问题描述】:

我正在尝试发送发布数据并从 api(qbittorrent) 接收 SID,以便稍后通过 get 请求发送。我目前遇到了 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 来向我发送 get 请求,我将非常欢迎 :)

【问题讨论】:

  • $postvars 最后会有一个额外的“&”。这是一个问题吗? ('用户名=管理员&密码=我的密码&')。另外,您需要循环来连接字符串还是只发送数组 - curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
  • $postvars = rtrim($postvars, '&amp;'); 在这里可能需要删除尾随的&符号。
  • 编辑了我的问题,仍然得到相同的结果。服务器仍然回复“ok”,我尝试输入错误的密码,却得到“Fails”
  • @jkns.co 我真的不知道需要发送什么,我假设是一个字符串,但我认为问题出在初始请求上,因为我得到了 OK 响应但更多关于返回的数据:\
  • json_decode 过程中可能有问题。执行echo json_last_error_msg(); 以查看阻止它从字符串返回 JSON 对象的原因。也可以echo $response; 在解码前查看字符串是什么。

标签: php json post curl get


【解决方案1】:

问题就在那里,变了:

curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_HEADER, true);

我得到了我的 json 响应!

【讨论】:

  • 但是您仍然发送了错误的请求。两行都做。