You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在代码中直接配置API Key调用Google Cloud Translation服务?

可以直接在代码中写入API Key调用翻译接口,你遇到的报错是因为新版官方客户端库的默认校验逻辑导致的,可通过以下方式解决:

解决方案

方法1:使用v2版本客户端库适配API Key调用

你之前用的setApiKey方法仅在2.x版本的google-cloud-translate客户端库可用,3.x及以上版本仅支持v3翻译API,必须使用服务账号JSON凭证,不支持API Key直接调用。
首先确认依赖版本(以Maven为例):

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
    <version>2.31.0</version> <!-- 请使用2.x分支的最新稳定版 -->
</dependency>

调整代码,手动跳过默认凭证校验即可:

import com.google.cloud.translate.Translate;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;
import com.google.auth.oauth2.GoogleCredentials;
import java.util.List;

public class TranslateDemo {
    public static void main(String[] args) {
        String API_KEY = "替换为你自己的API Key";
        Translate translate = TranslateOptions.newBuilder()
                .setApiKey(API_KEY)
                // 新增以下代码跳过默认凭证校验
                .setCredentials(new GoogleCredentials() {
                    @Override
                    public String getAuthenticationType() {
                        return null;
                    }
                    @Override
                    public GoogleCredentials createScoped(List<String> scopes) {
                        return this;
                    }
                })
                .build()
                .getService();

        // 执行翻译
        Translation translation = translate.translate(
                "¡Hola Mundo!",
                Translate.TranslateOption.targetLanguage("zh-CN")
        );
        System.out.println("翻译结果:" + translation.getTranslatedText());
    }
}

方法2:直接调用原生HTTP接口

如果不想调整客户端库依赖,可以直接发送HTTP请求调用翻译接口,避开凭证校验逻辑,示例如下:

import okhttp3.*;
import com.alibaba.fastjson.JSON;
import java.io.IOException;

public class TranslateHttpDemo {
    public static void main(String[] args) throws IOException {
        String API_KEY = "替换为你自己的API Key";
        String apiUrl = "https://translation.googleapis.com/language/translate/v2?key=" + API_KEY;

        // 构造请求体
        String requestJson = JSON.toJSONString(
                new java.util.HashMap<String, Object>(){{
                    put("q", "¡Hola Mundo!");
                    put("target", "zh-CN");
                    put("source", "es");
                }}
        );

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(apiUrl)
                .post(RequestBody.create(MediaType.parse("application/json"), requestJson))
                .build();

        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            String translatedText = JSON.parseObject(result)
                    .getJSONObject("data")
                    .getJSONArray("translations")
                    .getJSONObject(0)
                    .getString("translatedText");
            System.out.println("翻译结果:" + translatedText);
        }
    }
}

注意事项

  • 硬编码API Key存在泄露风险,生产环境建议将API Key存入配置中心或加密后的环境变量,不要直接写在业务代码中
  • 调用前请确认你已经在Google Cloud控制台开启了Cloud Translation API的访问权限,且API Key的IP、应用限制配置和你的运行环境匹配

内容的提问来源于stack exchange,提问作者newstudent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:27:02