Volley解析中文字符

来源:互联网 发布:tw域名 编辑:程序博客网 时间:2024/05/17 22:39

在使用Volley的时候,一般使用的是继承自Request<String>的StringRequest,而StringRequest中重写了两个方法:praseNetworkResponse和diliverResponse,可能还会有getParams方法,用于获取参数。

在praseNetworkResponse(NetworkResponse networkResponse)中,对networkResponse的解析是这样的:

result = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));

这里的第二个参数指定了string的编码类型,而HttpHeaderParser的parseCharset的方法源码是这样的:

public static String parseCharset(Map<String, String> 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";    }

它会对返回头进行解读,读取Content-Type的值,若服务器添加了header信息中的Content-Type值,则此方法返回此值,否则返回默认值"iso-8859-1"。

也就是说,若服务器返回的是中文(utf-8编码),且没有指定header的Content-Type,那么Volley解析就会乱码,无法得到中文字符。

解决方法也很简单,有两种方法:

1.在客户端对返回信息进行直接解码,指定解码类型为"utf-8":

result = new String(networkResponse.data,"utf-8");
2.服务器端设置header:

HttpHeaders headers = new HttpHeaders();header.setContentType("text/html;charset=utf-8");
这样就完成了。再见


0 0