在C#中有一个API构建,我能成功地从邮递员那里调用那个api,但我想用php做同样的事情。
邮差
使用Postman工具我可以成功上传文件。
但问题是我想用PHP代码做的事情。
我在PHP代码中尝试的内容:
$headers = array('DistributorCode:'.$_SERVER['HTTP_DISTRIBUTORAPIKEY'],'FolderName:'.$_SERVER['HTTP_DISTRIBUTORAPIKEY']);
$this->CallRestAPI('POST', 'http://192.168.1.55/api/upload' , array('attachment'=> file_get_contents(REPORTPATH . $_SERVER['HTTP_DISTRIBUTORAPIKEY'] . "\\07122017163625.zip")), $headers);
function CallRestAPI($method, $url, $data , $headers) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
}
$response = curl_exec($curl);
echo "Response:".$response;die;
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
case 200:
$error_status = "200: Success";
return ($data);
break;
case 404:
$error_status = "404: API Not found";
break;
case 500:
$error_status = "500: servers replied with an error.";
break;
case 502:
$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
break;
}
curl_close($curl);
echo $error_status;
die;
}