[Android]Volley源码分析(一)

时间:2022-09-15 16:25:38

一. 如何使用Volley?

1. 首先定义一个RequestManager类,用来在Android程序启动时对Volley进行初始化。RequestManager为单例类,因为只有在程序启动时调用,所以不需要考虑并发问题。

 /**
* Manager for the queue
*/
public class RequestManager { /**
* 请求队列
*/
private static RequestQueue mRequestQueue; /**
* 私有化构造函数
*/
private RequestManager() {
// no instances
} /**
* @param context 应用程序上下文
*/
public static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
} /**
* @return
* 请求队列
* @throws
* IllegalStatException if init has not yet been called
*/
public static RequestQueue getRequestQueue() {
if (mRequestQueue != null) {
return mRequestQueue;
} else {
throw new IllegalStateException("Not initialized");
}
}
}

2. 为了方便对请求的Body(PUT或POST请求时)及响应体进行解析,我们可以继承Volley的Request类,自定义一个通过Gson来解析请求与响应的Request。

 /**
* Wrapper for Volley requests to facilitate parsing of json responses.
*/
public class MyGsonRequest<T> extends Request<T>{ /** Charset for request. */
private static final String PROTOCOL_CHARSET = "utf-8";
/** Content type for request. */
private static final String PROTOCOL_CONTENT_TYPE =
String.format("application/json; charset=%s", PROTOCOL_CHARSET);
/**
* Gson parser
*/
private final Gson mGson;
/**
* Class type for the response
*/
private final Class<T> mResponseClass;
private final Object mRequestBody; /**
* Callback for response delivery
*/
private final Listener<T> mListener; /**
* @param method
* Request type.. Method.GET etc
* @param url
* path for the requests
* @param requestBody
* Q type instance as request body, if no request body needed set it to null
* @param responseClass
* expected class type for the response. Used by gson for serialization.
* @param listener
* handler for the response
* @param errorListener
* handler for errors
*/
public MyGsonRequest(int method
, String url
, Object requestBody
, Class<T> responseClass
, Listener<T> listener
, ErrorListener errorListener) { super(method, url, errorListener);
this.mRequestBody = requestBody;
this.mResponseClass = responseClass;
this.mListener = listener;
mGson = new Gson(); } @Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(mGson.fromJson(json, mResponseClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
} @Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
} @Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
} @Override
public byte[] getBody() {
try {
return mRequestBody == null ? null : mGson.toJson(mRequestBody).getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog
.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mGson.toJson(mRequestBody), PROTOCOL_CHARSET);
return null;
}
}
}

需要重写Request的以下方法:

1). parseNetworkResponse  通过Gson将服务器返回的Json字符串解析为你想要的对象 mGson.fromJson(json, mResponseClass)

2). deliverResponse  调用你自定义的实现了Response.Listener接口的回调方法onResponse

3). getBodyContentType  获取请求体的内容类型,如json类型,编码为utf-8

4). getBody 获取请求体的字节数组表示。 同样是通过Gson将你的请求体中对象转换为Json字符串来获取字节数组 mGson.toJson(mRequestBody).getBytes(PROTOCOL_CHARSET)

3. 接下来可以针对不同的领域模型定义一些客户端类,比如对用户的一些服务器请求操作可以定义一个UserManager类,实现注册、登录等功能。

public class UserManager {
    public static UserManager getInstance(){
if(mInstance == null) {
mInstance = new UserManager();
}
return mInstance;
}     public void register(Listener<String> listener, ErrorListener errorListener, User user){
Uri.Builder uriBuilder = Uri.parse(USER_BASE_URL).buildUpon();
String uri = uriBuilder.build().toString();
MyGsonRequest<String> request = new MyGsonRequest<String>(Method.POST
, uri
, user
, String.class
, listener
, errorListener); Log.v(TAG, request.toString());
RequestManager.getRequestQueue().add(request);
}
}

上述代码实例化了一个request,将这个request加入Volley的请求队列中,由Volley来负责对请求进行调度处理。

3. 然后别忘了在程序的Application类中,对Volley进行初始化

 public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RequestManager.init(this);
//其他初始化
}
...
}

4. 最后在具体的Activity中,就可以通过如下方式对服务器发起注册请求了。

//比如点击注册按钮,在onClick方法中调用
UserManager.getInstance().register(createLoginSuccessListener(),
createLoginErrorListener(), user);
//请求成功返回时调用
private Listener<String> createRegisterSuccessListener() {
return new Listener<String>() {
@Override
public void onResponse(String response) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
Toast.makeText(
RegisterActivity.this,
getString(R.string.msg_register_success),
Toast.LENGTH_SHORT).show(); }
};
} //请求失败时调用
private Response.ErrorListener createRegisterErrorListener() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
Toast.makeText(
RegisterActivity.this,
VolleyErrorUtil.getMessage(error, RegisterActivity.this),
Toast.LENGTH_SHORT).show();
}
};
}