如何使用cURL/PHP通过PUT方法向API发送JSON数据

5
我正在尝试使用cURL/PHP连接API。我需要使用PUT方法发送JSON数据到API。
这是我的参数: $data = array('__type' => 'urn:inin.com:connection:workstationSettings');
这是我进行cURL调用的方式:
private function _makeCall($method, $uri, $data = false, $header = NULL, &$httpRespond = array())
{
    $ch = curl_init();
    $url = $this->_baseURL . $uri;

    if( 
           ($method == 'POST' || $method == 'PUT') 
        && $data
    ){
        $jsonString = json_encode( $data );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsonString );
    }

    if($method == 'POST'){
        curl_setopt($ch, CURLOPT_POST, true);
    } elseif( $method == 'PUT'){
        curl_setopt($ch, CURLOPT_PUT, true);
    } else {
        if ($data){
            $url = sprintf("%s?%s", $url, http_build_query($data));
        }
    }  

    //disable the use of cached connection
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);

    //return the respond from the API
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //return the HEADER respond from the API
    curl_setopt($ch, CURLOPT_HEADER, true);

    //add any headers
    if(!empty($header)){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    //set the URL
    curl_setopt($ch, CURLOPT_URL, $url);

    //make the cURL call
    $respond = curl_exec($ch);

    //throw cURL exception
    if($respond === false){
        $errorNo = curl_errno($ch);
        $errorMessage = curl_error($ch);

        throw new ApiException($errorMessage, $errorNo);
    }   

    list($header, $body) = explode("\r\n\r\n", $respond, 2);

    $httpRespond = $this->_http_parse_headers($header);

    $result = json_decode($body, true);

    //throw API exception
    if(  $this->_hasAPIError($result) ){
        $errorCode = 0;
        if(isset($result['errorCode'])){
            $errorCode = $result['errorCode'];
        }
        throw new ApiException($result['message'], $errorCode);
    }

    return $result;
}

问题在于每次API接收到我的PUT请求时,它都会抱怨缺少一个参数,而我已经在我的$data数组中传递了这个参数。

我应该如何正确地使用$jsonString进行PUT?


什么出错了?你连接的是哪个API? - Andy Jones
1个回答

4

据我所知,这样使用PUT并不像你期望的那样行为表现。请改为尝试以下方法:

...
if($method == 'POST'){
    curl_setopt($ch, CURLOPT_POST, true);
} elseif( $method == 'PUT'){
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
...

参考:处理PHP中的PUT/DELETE参数


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接