Google Cloud Vision API 在 PHP AppEngine 上

Google Cloud Vision API on PHP AppEngine

我已经将 Google Cloud Vision api 与托管在私人 VPS 上的 php 应用程序一起使用了一段时间,没有出现任何问题。我正在将应用程序迁移到 Google AppEngine,现在 运行 遇到了问题。

我正在对 API 使用 CURL post,但它在 AppEngine 上失败了。我启用了计费功能,其他 curl 请求也没有问题。有人提到对 googleapis.com 的调用在 AppEngine 上不起作用,我需要以不同的方式访问 API。我无法在网上找到任何资源来确认这一点。

下面是我的代码,返回 CURL 错误 #7,无法连接到主机。

$request_json = '{
            "requests": [
                {
                  "image": {
                    "source": {
                        "gcsImageUri":"gs://bucketname/image.jpg"
                    }
                  },
                  "features": [
                      {
                        "type": "LABEL_DETECTION",
                        "maxResults": 200
                      }
                  ]
                }
            ]
        }';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://vision.googleapis.com/v1/images:annotate?key='.GOOGLE_CLOUD_VISION_KEY);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_json);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
    die("Error: $status, response $json_response, curl_error " . curl_error($curl) . ', curl_errno ' . curl_errno($curl));
}
curl_close($curl);
echo '<pre>';
echo $json_response;
echo '</pre>';

我将我的代码切换为使用 URLFetch (file_get_contents) 而不是 CURL。到目前为止工作得很好。我仍然不确定为什么 CURL 不起作用。

Google API 的 curl 请求在 PHP 中失败,因为 curl 使用套接字 API 并且 Google IP 被套接字阻止。此限制记录在 Limitations and restrictions:

Private, broadcast, multicast, and Google IP ranges are blocked


要发送您描述的 POST 请求,您可以使用 PHP 的流处理程序,提供必要的上下文来发送数据。我已经修改了 Issuing HTTP(S) Requests 中显示的示例以满足您的要求:

<!-- language: lang-php -->

$url = 'https://vision.googleapis.com/v1/images:annotate';
$url .= '?key=' . GOOGLE_CLOUD_VISION_KEY;

$data = [
    [
        'image' => [
            'source' => [
                'gcsImageUri' => 'gs://bucketname/image.jpg'
            ]
         ],
         'features' => [
             [
                 'type' => 'LABEL_DETECTION',
                 'maxResults' => 200
             ]
         ]
    ]
];

$headers = "accept: */*\r\nContent-Type: application/json\r\n";

$context = [
    'http' => [
        'method' => 'POST',
        'header' => $headers,
        'content' => json_encode($data),
    ]
];
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);

如果您决定使用 OAuth 等 API 密钥以外的身份验证方式,我还建议您阅读 Asserting identity to Google APIs