【问题标题】:What is the appropriate way to communicate with Google API from Spring back-end?从 Spring 后端与 Google API 进行通信的适当方式是什么?
【发布时间】:2018-02-08 16:34:33
【问题描述】:

我正在尝试使用 Spring 从 Angular 创建一个翻译器。所以在春天我创建了这个端点

package com.vir.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.vir.exception.ApiError;
import com.vir.model.iTranslator;
import com.vir.service.iTranslateProcessorService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;

@RestController
@RequestMapping("/api")
@Api(tags = "iTranslate")
public class iTranslateController {

    @Autowired
    @Qualifier("iTranslatorService")
    private iTranslateProcessorService itranslateProcessorService;


    @ApiOperation(value = "Translate a text input.")
    @ApiResponse(code = 400, message = "Generic error", response = ApiError.class)
    @PostMapping(value = "/iTranslate", produces = MediaType.APPLICATION_JSON_VALUE)
    public iTranslator iTranslate(@RequestBody(required = true) String text, @RequestBody(required = true) String target) {
        return itranslateProcessorService.process(text, target);
    }
}

我还制作了 ItranslateProcessorService 接口,它将调用 iTranslator 模型。我的问题是,在该模型中,我在哪里调用 google API?如何使它返回谷歌 API 返回的翻译或 json 文件? Here is the documentation of the google API

任何指向正确方向的方法都会有所帮助,谢谢。

【问题讨论】:

    标签: java spring api backend google-translate


    【解决方案1】:

    这显然是您将发送的 HTTP 请求。您的接口实现将建立一个 HTTP 连接、发布请求并返回响应。

    请确保汇集这些 HTTP 连接。创建它们的成本很高。

    请务必考虑如果 Google 翻译调用超时或失败会发生什么。

    我不同意您选择的返回类型:我建议使用 ResponseEntity<T> 并使泛型类型对您的问题有意义。

    您需要知道 Google 翻译服务是免费的。如果您打算在一段时间内进行多次翻译,则必须付费。

    【讨论】:

    • 谢谢!为什么我应该使用'code'(ReponseEntity)?另外,如果谷歌调用超时或失败,我应该研究接口实现和处理的任何 Spring 库?
    • 返回界面对我来说似乎完全错误。您希望客户对此做什么?如果您使用 ResponseEntity,Spring 将负责转换为用户指定的 MIME 类型。它会根据客户的需要将您的响应对象转换为 XML 或 JSON。 HTTP 客户端应该处理超时。如果您希望控制器处理它并通知调用者,您的接口应该抛出异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多