为什么用Android Volley时返回的中文是乱码,而postman却显示正常

那是因为当服务器返回数据的header中没有设置charset=UTF-8的话,Volley会默认将数据传承ISO-8859-1,下面是源码:


StringRequest.java

protected Response parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        Log.e("-----JSON----", parsed);
        if(this.needCache && !parsed.equals(DataCache.getDataCache().queryCache(this.url))) {
            DataCache.getDataCache().saveToCache(this.url, parsed);
        }
    } catch (UnsupportedEncodingException var4) {
        parsed = new String(response.data);
    }

    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}


HttpHeaderParser.java
public static String parseCharset(Map headers) {
    String contentType = (String)headers.get("Content-Type");
    if(contentType != null) {
        String[] params = contentType.split(";");

        for(int i = 1; i < params.length; ++i) {
            String[] pair = params[i].trim().split("=");
            if(pair.length == 2 && pair[0].equals("charset")) {
                return pair[1];
            }
        }
    }

    return "ISO-8859-1";
}

你可能感兴趣的:(为什么用Android Volley时返回的中文是乱码,而postman却显示正常)