首页 » 文章 » spring boot调用谷歌翻译收费api

最近发现谷歌免费api有次数限制,所以只好调用他们收费api,还好他们免费试用,给了很多美金。

1.引入api的以来

   <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-translate</artifactId>
            <version>1.76.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.1-jre</version>
        </dependency>

2.创建一个service的凭据,按这个链接操作:https://cloud.google.com/docs/authentication/getting-started
3.下载平局的json,然后java 代码

@Component
public class Translate2 {

    @Value(value = "classpath:my.json")
    private Resource googleJson;

    private TranslateOptions translateOptions;

    /**
     * 初始化消息配置
     *
     * @throws IOException
     */
    @PostConstruct
    public void initFireBase() throws IOException {

           List<String> scops = new ArrayList<>();
        scops.add("https://www.googleapis.com/auth/cloud-platform");
        GoogleCredentials credentials = GoogleCredentials.fromStream(googleJson.getInputStream());
//                .createScoped(scops);

          translateOptions = TranslateOptions.newBuilder().setCredentials(credentials).build();
    }


    public String translateText(String text) throws IOException {
        if (StringUtils.isEmpty(text)) {
            text = "Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again. ";
        }

        return translateOptions.getService().translate("test", Translate.TranslateOption.sourceLanguage("en"),
                Translate.TranslateOption.targetLanguage("zh-CN")).getTranslatedText() ;
    }
}

仅有一条评论

  1. along along

    你好 有联系方式吗 项目也遇到了这个问题 请教下

添加新评论