【问题标题】:Google Cloud Vision API 400 Invalid JSON PayloadGoogle Cloud Vision API 400 无效的 JSON 负载
【发布时间】:2018-07-31 11:16:12
【问题描述】:

我已经输入了所有必填字段,因为他们在https://cloud.google.com/vision/docs/detecting-labels#vision-label-detection-protocol 的协议部分上写了我的代码。但是,它仍然返回 400 错误。

<?php
if(!isset($googleapikey)){
    include('settings.php');
}
function vision($query){
    global $googleapikey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,'https://vision.googleapis.com/v1/images:annotate?key='.$googleapikey);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
    $result = curl_exec ($ch);
    curl_close ($ch);
    return $result;
}

$vdata = array();
$vdata['requests'][0]['image']['source']['imageUri'] = 'https://cloud.google.com/vision/docs/images/ferris-wheel.jpg';
$vdata['requests'][0]['features'][0]['type'] = 'LABEL_DETECTION';
echo vision(json_encode($vdata));
?>

【问题讨论】:

  • 试试json_encode($vdata, JSON_UNESCAPED_SLASHES)。默认情况下,json_encode() 转义可能与 Google API 不兼容的正斜杠(例如 http://
  • 还是返回400错误

标签: php json api curl google-cloud-vision


【解决方案1】:

您对 Cloud Vision API 的请求中的唯一错误是您没有设置 HTTP 标头字段 Content-type: application/json 的属性,因为您没有将其分配给正确的变量 (您指向的是$curl 而不是$ch):

// Insread of this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
// Use this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));

运行旧代码时显示的错误如下所示,这表明查询未将内容数据理解为 JSON。

Cannot bind query parameter. Field '{\"requests\":[{\"image\":{\"source\":{\"imageU ri\":\"https://cloud' could not be found in request message.

作为旁注,让我向您推荐Client Libraries for Cloud Vision API,它有一些nice documentation,可以让您在通过脚本使用Google Cloud Platform 中的一些API 时更轻松。在这种情况下,您不需要强制使用curl 命令,并且可以使用非常简单(且易于理解)的代码来获得相同的结果,例如:

<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Vision\VisionClient;

$projectId = '<YOUR_PROJECT_ID>';
$vision = new VisionClient([
    'projectId' => $projectId
]);

$fileName = 'https://cloud.google.com/vision/docs/images/ferris-wheel.jpg';
$image = $vision->image(file_get_contents($fileName), ['LABEL_DETECTION']);
$labels = $vision->annotate($image)->labels();

echo "Labels:\n";
foreach ($labels as $label) {
    echo $label->description() . "\n";
}
?>

【讨论】:

  • 天哪,这是个小错误!非常感谢!
猜你喜欢
  • 2016-06-19
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 2017-11-26
  • 2017-07-07
  • 2023-04-03
  • 2019-08-04
相关资源
最近更新 更多