【问题标题】:PUT Request via CURL通过 CURL 的 PUT 请求
【发布时间】:2015-10-05 12:50:25
【问题描述】:

我正在尝试发出 CURL PUT REQUEST,我的代码如下所示:

public function assignProfile($token, $organizationId, $profileId)
    {
        //define enviroment and path
        $host = enviroment;
        $path = "/admin/organizations/".$organizationId."/users";       

        $data_string = '["'.$profileId.'"]';        

        // set up the curl resource
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $host.$path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
            'Content-Type: application/json',                                                                                
            'Authorization: Bearer '.$token.'',      
            'Content-Length: ' . strlen($data_string)                                                                       
        ));

        echo "<br>OK<br>";
        // execute the request      
        $output = curl_exec($ch);       

        // return ID for a new case
        $output = json_decode($output);                 
        var_dump($output);
    }   

当我 var_dump $path$host、甚至 $data_string 时,每个部分看起来都是正确的。然而var_dump()最后只抛出NULL

我预计我做错了什么或错过了一些非常重要的事情。 我可以请你给点建议吗?

谢谢

编辑: 我用它做什么:

// define 
define("Audavin","here is some uniqe ID");
.
.
.
$Users = new Users;
// this return Auth token ( I verify this work with echo )
$token = $Users->authorization();  
// Calling method mentioned above
$Users->assignProfile($token,"here is org id", Audavin);

【问题讨论】:

  • $output = curl_exec($ch); 的内容是什么?此外,在打开 PHP 标记后立即将错误报告添加到文件顶部,例如 &lt;?php error_reporting(E_ALL); ini_set('display_errors', 1); 然后是其余代码,以查看它是否产生任何结果。
  • 嘿@PedroLobito,我在我的文件顶部添加了错误报告和显示错误,不幸的是它没有显示任何附加错误。关于我如何调用此方法,我编辑了我的问题。关于内容我不确定你的意思:(
  • $output = curl_exec($ch); 之后立即执行echo 会显示什么?
  • 如果我将它转储为字符串(“”),它只会回显空白字符串,它看起来就像我没有收到来自服务器的响应
  • 好!你知道问题出在哪里,从那里开始调试,之后发布任何更新

标签: php curl put


【解决方案1】:
  1. 我首先要确保您发出请求的 URL 确实有效并返回有效响应,您可以使用简单的 REST 客户端(例如 POSTMAN chrome 扩展程序)来做到这一点
  2. 如果您确实收到了回复,请尝试查看它是否确实是一个有效的 JSON,如果不是,这可能就是您没有从 json_decode 获得任何回复的原因(更多关于返回值:http://php.net/manual/en/function.json-decode.php)李>
  3. 最后,建议您在代码末尾添加 curl_close($ch) 以确保释放 curl 句柄。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多