2

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

我正在使用 CURL 发布到 API,但它在 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>';
4

2 回答 2

0

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

私有、广播、多播和 Google IP 范围被阻止


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

<!-- 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 。

于 2017-02-16T21:05:49.050 回答
0

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

于 2016-04-29T17:56:14.120 回答