drblhw5731 2016-02-27 20:37
浏览 810

PHP curl POST请求与JSON响应

I'm trying to send post data and receive an SID from an api(qbittorrent) to send with a get request later. I'm currently stuck with an OK response but the json is NULL. Here's my code:

<?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);
?>

You can see the API documentaiton here https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation#authorization

I was able to get the json using powershell as simply as :

$prms = @{username="Admin";password="mypassword"}
$res = Invoke-WebRequest https://192.123.123.123:8080/login -Method POST -Body prms -UseBasicParsing

but I'm unable to do so with php! If you also feel like heading me right for the get request using the SID as a cookie, i'll be more than welcome :)

  • 写回答

1条回答

  • duanjia8215 2016-02-27 21:59
    关注

    The problem was lying there, changed:

    curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
    

    to

    curl_setopt($ch, CURLOPT_HEADER, true);
    

    And I got my json response!

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler