grpc 谷歌登录失败

grpc Google login failure

本文关键字:失败 登录 谷歌 grpc      更新时间:2023-10-16

我正在尝试使用谷歌的云语音API创建一个应用程序。我克隆了所有存储库,并在C++中创建了一个非常简单的客户端应用程序。

#include <grpc++/grpc++.h>
#include "google/cloud/speech/v1/cloud_speech.grpc.pb.h"
namespace gs=google::cloud::speech::v1;
using gs::Speech;
using gs::RecognizeResponse;
using gs::RecognizeRequest;
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
int main(int argc, char** argv) {
    try{
        auto channel_creds = grpc::GoogleDefaultCredentials();
        auto channel = grpc::CreateChannel("speech.googleapis.com:443", channel_creds);
        auto stub = Speech::NewStub(channel);
        RecognizeResponse res;
        RecognizeRequest req;
        ClientContext ctx;
        auto status = stub->Recognize(&ctx, req, &res);
        if(status.ok())
        {
            std::cout << "ok" << std::endl;
        } else {
            std::cout << status.error_code() << ": " << status.error_message() << std::endl;
        }
    }catch(const std::exception& e)
    {
        std::cout<<e.what()<<std::endl;
    }
    std::cin.get();
}

这编译正常,但在执行时会导致以下错误消息:

16:请求具有无效的身份验证凭据。预期的 OAuth 2 访问令牌、登录 Cookie 或其他有效的身份验证凭据。请参阅 https://developers.google.com/identity/sign-in/web/devconsole-project。

我创建了一个服务帐户,并将其 json 密钥文件放在 env 变量"GOOGLE_APPLICATION_CREDENTIALS"旁边的正确文件,我很确定它已被读取(因为如果我删除它,它只会崩溃(。我还在线启用了语音 API。我没有想法,因为无论我做什么我都无法让它工作。我错过了什么吗?

经过更多的尝试和阅读更多的示例代码,我终于自己找到了原因。我不得不使用不同的网址。将"speech.googleapis.com:443"更改为"speech.googleapis.com"会导致不同的错误,但连接和登录有效。

正确设置此函数的所有参数并提供实际音频数据将返回可用结果。我没想到端口会有所不同,考虑到这两个 URL 都在许多示例程序中,并且 grpc 使用 http2(而 http2 又使用端口 443(。

重要提示:确保不包含用于 Google 服务的端口。