0
votes

I am developing an android app where I have to convert user's speech to text(using google cloud speech API) and then that text into another language (using google cloud translation API).

Now,

I have successfully converted user's speech into text but the issue is while converting that text into another language I get nothing in the response body. When I send request to cloud translation API using my browser (eg, Google Chrome) then it returns as expected (shown below).

The request that I sent: 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"
   }
  ]
 }
}

But the problem is when I send the same request from my app using OkHttp3 then it returns following response

Response{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 vary: Origin vary: X-Origin vary: Referer date: Sun, 30 Sep 2018 08:27:40 GMT server: ESF cache-control: private x-xss-protection: 1; mode=block x-frame-options: SAMEORIGIN x-content-type-options: nosniff alt-svc: quic=":443"; ma=2592000; v="44,43,39,35" OkHttp-Sent-Millis: 1538296059111 OkHttp-Received-Millis: 1538296060590

okhttp3 dependency is shown below

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

My code for translating text is shown below

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

            }
        });
    }

Note: Even I receive the code 200 but still there is nothing in the message of the response

1

1 Answers

2
votes

response.message() is the HTTP status message, like "OK" from 200 OK. You should also check response.code() which will be numeric. response.body.toString() is for debugging

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

You want

String res = response.body().string()