[英]how to send JSON data to an API using PUT method via cURL/PHP
我正在嘗試使用cURL / PHP連接到API。
我需要在發送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這種方式並不像你期望的那樣。 試試這個:
...
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
} elseif( $method == 'PUT'){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.