【发布时间】:2018-04-08 07:03:21
【问题描述】:
如何将以下 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, “图片”: [ { “错误”: { "description": "无效的图像数据。支持的格式为 JPG 和 PNG。", “error_id”:“输入错误” } } ], “图像处理”:1 }
之前:
{ “错误”: { “代码”:400, "description": "收到无效的 JSON 内容。无法解析。", “error_id”:“parameter_error” }, “图像处理”:0 }
感谢您的帮助!
【问题讨论】:
-
您正在发送
$data,但您的Content-Length标头假装请求的大小仅为<json-string>的大小,而这只是$data的一部分。 -
确定组装请求正文的正确长度应该真正属于 inside 这样的
send方法......但首先,我会尝试不使用它 - cURL当您将数组数据结构传递给 CURLOPT_POSTFIELDS 时,应该能够找出正确的值并自动附加该标头 -
(实际上,您似乎没有发送 $data,而是在循环,然后才将实际上传文件添加到数据结构中......但无论如何,您的计算内容长度似乎为时过早...)
-
谢谢@CBroe,我的问题有点不同。我在
CURLFile中为 $postname 添加了错误的值
标签: php json curl watson visual-recognition