如何使用PUT方法通过cURL / PHP将JSON数据发送到API
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用PUT方法通过cURL / PHP将JSON数据发送到API,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1976字,纯文字阅读大概需要3分钟。
内容图文
![如何使用PUT方法通过cURL / PHP将JSON数据发送到API](/upload/InfoBanner/zyjiaocheng/787/9929cfff6e6e4da1af760e7d4be24545.jpg)
我正在尝试使用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');
...
参考:Handling PUT/DELETE arguments in PHP
内容总结
以上是互联网集市为您收集整理的如何使用PUT方法通过cURL / PHP将JSON数据发送到API全部内容,希望文章能够帮你解决如何使用PUT方法通过cURL / PHP将JSON数据发送到API所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。