您的位置:首页 > Web前端 > JavaScript

Volley获取json数据乱码问题

2016-07-18 11:05 337 查看
现在Android开发的网络请求库很多,这里不一一列举了(原因:别的我没用过,不知道怎么说,哈~哈~~)。

Volley是我们常用的一个网络请求库。为什么用Volley?这里不做介绍(原因:别的没用过,其实Volley好在哪里我也不知道。嘿~嘿~~)

使用Volley的同学,很容易遇到乱码问题,对不对?我没说错吧?你遇到了吗?

乱码问题的产生原因,想必大家都知道!这里我不多说。(原因:我怕说了也白说,其实我怕我说不清除,嘎~嘎~~)

来,让我们看看遇到乱码问题怎么解决吧!

网络请求的时候你怎么用的,是这样用的吗?

//网络请求时,new 一个JsonObjectRequest对象,

JsonObjectRequest jbr=new JsonObjectRequest(url, jsonRequest, listener, errorListener);
1
2
3
4

可是返回的数据乱码了吗?没乱?这可是不代表你干什么都不乱啊。用他做第三方登录(这里指微信登录)试试,看乱不乱。

乱了?我们看看怎么处理。

复写这个Volley中JsonObjectRequest这个类,写个自定义类CharsetJsonRequest如下:

package com.xxxxx.net;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;

//如果返回头中没有Charset,默认UTF-8
public class CharsetJsonRequest extends JsonObjectRequest {

public CharsetJsonRequest(String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}

public CharsetJsonRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}

@Override
protected 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));
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

上面我们在parseNetworkResponse 中制定编码为“UTF-8”,看看,你的乱码问题是不是解决了呢?

当然现在你不该new JsonObjectRequest,应该换成这样请求网络了:

CharsetJsonRequest jbr=new CharsetJsonRequest(url, jsonRequest, listener, errorListener);
1

不知道你的问题解决了没。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: