解决Volley请求网络数据返回的数据乱码

时间:2022-02-28 21:45:58

本人可参考http://tieba.baidu.com/p/4039693566

以往一般我们如下写就可以了

StringRequest request=new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String result) {
    myModelList= JSON.parseObject(result, new TypeReference<List<MyModel>>() {
        });

    myModelAdapter= newMyModelAdapter(myModelList);
        list_market.setAdapter(myModelAdapter);
      }
  },new Response.ErrorListener(){
  @Override
  public void onErrorResponse(VolleyError volleyError) {
}
});
Volley.newRequestQueue(activity).add(request); 但具体原因result为什么会出现乱码没有时间去研究,解决方法,新建一个类如
MyStringRequest重写volley的StringRequest,如下,重写完后,将上面的StringRequest替换成MyStringRequest
public class MyStringRequest extends StringRequest {

    public MyStringRequest(String url, Response.Listener<String> listener,
Response.ErrorListener errorListener) {
super(url, listener, errorListener);
} /**
* 重写以解决乱码问题
*/
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String str = null;
try {
str = new String(response.data, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Response.success(str,
HttpHeaderParser.parseCacheHeaders(response));
}
}