square / okhttp

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.
https://square.github.io/okhttp/
Apache License 2.0
45.86k stars 9.16k forks source link

OkHttp reply me not in UTF8 but in Percent Encoding #6028

Closed Master-Antonio closed 4 years ago

Master-Antonio commented 4 years ago

im calling a GET Api (API of ModernMTT) with OkHttp (Last version), my problem is that the reply from the server is not in UTF-8 but in Percent Encoding, and i dont understand why, i try to set the Content-Type to UTF-8 without result. I tried also to Decode without result. URLDecoder.decode(stringDecoded, StandardCharsets.UTF_8) From CURL and Postman the server reply good. So the problem is on OkHttp. My code

    public static String translate(String string) throws IOException {
            OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(new FixEncodingInterceptor()).build();
            Request request = new Request.Builder()
                    .url("https://api.modernmt.eu/translate?source=" + sourceLanguage + "&target=" + targetLanguage + "&q=" + string)
                    .method("GET", null)
                    .addHeader("MMT-ApiKey", apiKey)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                String stringTranslated= Objects.requireNonNull(response.body()).string();
                ResponseMTT responseMTT = new Gson().fromJson(stringTranslated, ResponseMTT.class);
                StandardCharsets.UTF_8));
                return responseMTT.getData().getTranslation();
            }
        }

The response.body.string() return this format:

`%22Sconto%20del%2020%:%20%3CPAColor0xFF66CC33%3EUtilities%20%E2%86%92%20Capacity%20of%20load%3CPAOldColor%3E.`
Master-Antonio commented 4 years ago

I fixed doing:

HttpUrl httpurl = new HttpUrl.Builder()
                .scheme("https")
                .host("api.modernmt.eu")
                .addPathSegment("translate")
                .addQueryParameter("source", sourceLanguage)
                .addQueryParameter("target", targetLanguage)
                .addQueryParameter("q",string)
                .build();

and after in request .url(httpurl)

I dont understand the difference, but creating the object HttpUrl now the answer from server is in correct way.

yschimke commented 4 years ago

This is a better question for stackoverflow, this isn't a reproducible bug given the request requires a auth token.