【问题标题】:OkHttp reply me not in UTF8 but in Percent EncodingOkHttp 不是用 UTF8 而是用百分比编码回复我
【发布时间】:2020-08-22 23:53:49
【问题描述】:

我用 OkHttp(最新版本)调用 GET Api(ModernMTT 的 API),我的问题是来自服务器的回复不是 UTF-8 而是百分比编码,我不明白为什么,我尝试设置UTF-8 中的 MINE 没有结果。 来自 CURL 和 Postman 的服务器回复良好。 所以问题出在 OkHttp 上。 我的代码

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();
        }
    }

response.body.string() 返回这种格式:

%22Sconto%20del%2020%:%20%3CPAColor0xFF66CC33%3EUtilities%20%E2%86%92%20Capacity%20of%20load%3CPAOldColor%3E.

【问题讨论】:

  • Content-Type 标题行包含什么?

标签: java rest api okhttp machine-translation


【解决方案1】:

您可以尝试将“Accept-Charset”标头设置为 UTF-8 并测试您的代码吗?我假设 Postman 将接受字符集标头默认为 utf-8。

【讨论】:

    猜你喜欢
    • 2016-08-25
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2018-11-18
    • 2018-11-22
    相关资源
    最近更新 更多