You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Java请求API返回重音字符在TextView显示乱码如何解决

问题根因

乱码由Volley默认编码解析逻辑导致:当接口响应头Content-Type未显式声明charset=utf-8时,StringRequest会默认使用ISO-8859-1单字节编码解析响应体。服务端实际返回的是UTF-8编码的多字节重音字符,编码不匹配就会出现你看到的字符错乱,和TextView控件本身无关。

修复方案

两种方案二选一即可:

方案1:单请求强制指定UTF-8解析

重写StringRequest的parseNetworkResponse方法,强制使用UTF-8编码转码响应内容,替换你原有创建StringRequest的代码:

StringRequest request = new StringRequest(
        Request.Method.GET,
        url,
        future,
        future
) {
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String parsedString;
        try {
            parsedString = new String(response.data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            parsedString = new String(response.data);
        }
        return Response.success(parsedString, HttpHeaderParser.parseCacheHeaders(response));
    }
};
  • 如果项目minSdkVersion >= 19,可以直接用StandardCharsets.UTF_8替换"UTF-8",不需要捕获异常。

方案2:全局配置Volley默认编码

如果项目所有接口均使用UTF-8编码,可在初始化RequestQueue时全局配置编码规则,无需逐个请求修改:

RequestQueue queue = Volley.newRequestQueue(context, new HurlStack() {
    @Override
    public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
        HttpResponse response = super.executeRequest(request, additionalHeaders);
        HttpEntity entity = response.getEntity();
        if (entity != null && entity.getContentType() != null) {
            String contentType = entity.getContentType().getValue();
            if (!contentType.contains("charset=")) {
                entity.setContentType(contentType + ";charset=utf-8");
            }
        }
        return response;
    }
});
注意事项
  • 修复逻辑只需要放在网络响应解析层即可,Gson解析、TextView赋值环节不需要做任何额外编码转换。
  • 不要尝试对已经乱码的字符串做反向转码修复,只要保证网络层解析编码和服务端返回编码一致,后续全链路都不会出现乱码。

内容的提问来源于stack exchange,提问作者Kepler Batista

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 04:12:56