grpc Google 登录失败

grpc Google login failure

我正在尝试使用 google 的云语音 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: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

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

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

正确设置此功能的所有参数并提供实际音频数据returns 可用结果。我没想到端口会有所作为,考虑到 URLs 在许多示例程序中并且 grpc 使用 http2(反过来使用端口 443)。

重要提示:确保您没有包含用于 google 服务的端口。