0

我如何必须将以下 curl 命令“翻译”为有效的 php curl 函数?

curl -X POST 
     -F "images_file=@fruitbowl.jpg" 
     -F parameters=%7B%22classifier_ids%22%3A%5B%22testtype_205919966%22%5D%2C%22threshold%22%3A0%7D  
     'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={key}&version=2016-05-20'"

看来我做错了什么,我无法弄清楚问题所在:

$method = 'POST'
$url = 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=<myApiKey>&version=2016-05-20'
$data = array(
    array(<file-information>),
    array(<json-string>),
)
$header = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen(<json-string>),
                )
        )

public function send($method, $url, $data = null, $header = null)
{
    $curl = curl_init();

    switch ($method) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data) {
                $postData = $this->renderPostData($data);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
            }
            break;
    }

    if($header) {
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
}

protected function renderPostData($data)
{
    $postData = array();
    foreach ($data as $file) {
        if ($file['isFile']) {
            if(pathinfo($file['path'], PATHINFO_EXTENSION) == 'zip'){
                $postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);
            }
            else {
                $postData[$file['name']] = new \CURLFile($file['path'], 'application/octet-stream', $file['name']);
            }
        } else {
            // this contains the json encoded string
            $postData[$file['name']] = $file['path'];
        }
    }

    return $postData;
}

我尝试了几种变体,现在 Watson Visual Recognition API 错误是:

{ "custom_classes": 0, "images": [ { "error": { "description": "无效的图像数据。支持的格式是 JPG 和 PNG。", "error_id": "input_error" } } ], "images_processed" : 1 }

之前是:

{ "error": { "code": 400, "description": "收到无效的 JSON 内容。无法解析。", "error_id": "parameter_error" }, "images_processed": 0 }

谢谢您的帮助!

4

1 回答 1

0

我的问题是这一行:

$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);

最后一个参数是 $postname。因此,要解决此问题,我必须将此行更改为:

$postData[$file['name']] = new \CURLFile($file['path'], mime_content_type($file['path']), basename($file['path']));

$header它起作用了-在我也完全消除了错误之后

:)

于 2017-10-27T11:16:30.943 回答