how to send JSON data to an API using PUT method via cURL/PHP

回眸只為那壹抹淺笑 提交于 2019-12-10 15:13:00

问题


I am trying to connect to an API using cURL/PHP.

I need to PUT a method to this API while sending JSON data.

Here is my parameter $data = array('__type' => 'urn:inin.com:connection:workstationSettings');

Here is how I am doing the cURL call

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;
}

The issue is that every time the API receive my PUT request it complains that there is a missing parameter which I am passing in my $data array

How can I PUT the $jsonString correctly?


回答1:


From what I understand, using PUT this way doesn't behave the way you would expect. Try this instead:

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

Reference: Handling PUT/DELETE arguments in PHP



来源:https://stackoverflow.com/questions/30085967/how-to-send-json-data-to-an-api-using-put-method-via-curl-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!