【发布时间】:2015-07-17 03:14:00
【问题描述】:
我正在尝试使用 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?
【问题讨论】:
-
错误是什么?您要连接到哪个 API?