无法在php中为FileUpload调用REST API

时间:2017-12-07 14:09:36

标签: php rest api

在C#中有一个API构建,我能成功地从邮递员那里调用那个api,但我想用php做同样的事情。

邮差

标题信息需要在调用api之前设置 enter image description here

附件参数中的实际文件上载。 enter image description here

使用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;
    }

1 个答案:

答案 0 :(得分:2)

您可以从右上角的邮递员处获取代码。 "代码"按钮。它会根据您的需要生成任何语言的代码。

the code button you should choose curl then you can copy the code