Volley JsonObjectRequest 获取json字符串乱码

来源:互联网 发布:网络接口都有哪些 编辑:程序博客网 时间:2024/04/26 05:34

在使用Volley过程遇到一个问题,使用JsonObjectRequest访问http://www.weather.com.cn/adat/cityinfo/101200101.html 得到的 数据是乱码,查看源码发现在JsonObjectRequest类中代码如下

@Overrideprotected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {try {<span style="color:#ff6666;">String jsonString = new String(response.data,HttpHeaderParser.parseCharset(response.headers));</span>return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));} catch (UnsupportedEncodingException e) {return Response.error(new ParseError(e));} catch (JSONException je) {return Response.error(new ParseError(je));}}
这行代码是设置编码的方法,参数是响应的头信息 进去看一下

 /**     * Returns the charset specified in the Content-Type of this header,     * or the HTTP default (ISO-8859-1) if none can be found.     */    public static String parseCharset(Map<String, String> headers) {        String contentType = headers.get(HTTP.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) {                    if (pair[0].equals("charset")) {                        return pair[1];                    }                }            }        }        return HTTP.DEFAULT_CONTENT_CHARSET;    }

从注释就可以看出,这段代码会从头信息获取编码,如果没有的话就会默认设置成ISO-8859-1,此时我们的解决方法有两个

1.修改服务端编码ISO-8859-1,此方法此时不使用,因为服务端代码并不是我们编写的,

2.修改本地编码,自己定义类继承JsonObjectRequest,自由设置编码

public class MyJsonObjectRequest extends JsonObjectRequest {public MyJsonObjectRequest(int method, String url, JSONObject jsonRequest,Listener<JSONObject> listener, ErrorListener errorListener) {super(method, url, jsonRequest, listener, errorListener);}public MyJsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,            ErrorListener errorListener) {        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,                listener, errorListener);    }@Overrideprotected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {try {String jsonString = new String(response.data,"utf-8");return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));} catch (UnsupportedEncodingException e) {return Response.error(new ParseError(e));} catch (JSONException je) {return Response.error(new ParseError(je));}}}


使用我们定义的MyJsonObjectRequest就可以轻松实现转码

0 0