如何使用PUT方法通过cURL / PHP将JSON数据发送到API
发布时间:2020-12-13 22:57:38 所属栏目:Linux 来源:网络整理
导读:我正在尝试使用cURL / PHP连接到API. 我需要在发送JSON数据时为此API提供一个方法. 这是我的参数 ????$data = array(‘__ type’=’urn:inin.com:connection:workstationSettings’); 这是我如何进行cURL调用 private function _makeCall($method,$uri,$d
我正在尝试使用cURL /
PHP连接到API.
我需要在发送JSON数据时为此API提供一个方法. 这是我的参数 这是我如何进行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("rnrn",$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,true); } elseif( $method == 'PUT'){ curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'PUT'); ... 参考:Handling PUT/DELETE arguments in PHP (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |