0

我正在开发一个 android 应用程序,我必须将用户的语音转换为文本(使用谷歌云语音 API),然后将该文本转换为另一种语言(使用谷歌云翻译 API)。

现在,

我已经成功地将用户的语音转换为文本,但问题是在将该文本转换为另一种语言时,我在响应正文中一无所获。当我使用浏览器(例如 Google Chrome)向云翻译 API 发送请求时,它会按预期返回(如下所示)。

我发送的请求:https ://translation.googleapis.com/language/translate/v2?target=es&key=MY_API_KEY&q=this%20is%20the%20text%20which%20is%20need%20to%20be%20translated

{
"data": {
"translations": [
   {
    "translatedText": "este es el texto que debe ser traducido",
    "detectedSourceLanguage": "en"
   }
  ]
 }
}

但问题是当我使用 OkHttp3 从我的应用程序发送相同的请求时,它会返回以下响应

响应{protocol=h2, code=200, message=, url= https://translation.googleapis.com/language/translate/v2?target=es&key=MY_API_KEY&q=this%20is%20the%20text%20which%20is%20need %20to%20be%20translated }

body = OkHttp-Selected-Protocol: h2 content-type: application/json; charset=UTF-8 变化:来源变化:X-Origin 变化:引用日期:Sun,2018 年 9 月 30 日 08:27:40 GMT 服务器:ESF 缓存控制:私有 x-xss-protection:1;mode=block x-frame-options: SAMEORIGIN x-content-type-options: nosniff alt-svc: quic=":443"; 马=2592000;v="44,43,39,35" OkHttp-Sent-Millis: 1538296059111 OkHttp-Received-Millis: 1538296060590

okhttp3 依赖如下所示

compile 'com.squareup.okhttp3:okhttp:3.11.0'

我的文本翻译代码如下所示

private void getTranslation(String url) {
    OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Toast.makeText(SpeechService.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String res = response.body().toString();
                String mess = response.message(); //gets nothing as message response

            }
        });
    }

注意:即使我收到代码 200 但响应消息中仍然没有任何内容

4

1 回答 1

2

response.message() 是 HTTP 状态消息,如 200 OK 中的“OK”。您还应该检查 response.code() 这将是数字。response.body.toString() 用于调试

  @Override public String toString() {
    return "Response{protocol="
        + protocol
        + ", code="
        + code
        + ", message="
        + message
        + ", url="
        + request.url()
        + '}';
  }

你要

String res = response.body().string()
于 2018-09-30T13:51:04.493 回答