Activity代码:
Volley 网络通信框架 * 完全异步 * 怎么实现呢
* 1:因为Volley是并发的跟Handler里面消息机制一样
* 消息队列管理 消息 * RequestQueue 管理 Request(StringRequest,ImageRequest)
* 最后不要忘记add进去 *
* Volley请求图片有三种方式 * 1:ImageRequest * 2:ImageLoader * 3:NetWorkImageView * 自定义Request怎么写? * 通过参考StringRequest * private final ListenermListener; 用来保存数据的回调接口
* deliverResponse()方法成功过后的处理
* parseNetworkResponse()方法请求中的处理
*
* Gson gson = new Gson();
*
* gson.fromJson(jsonStr,T.class);
* type java===>T * ArryList
// 自定义Request
private void getZDYRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this); MyGsonRequestmyGson = new MyGsonRequest<>(Request.Method.GET, mUrl, null,
MyData.class, new Response.Listener() {
@Override
public void onResponse(MyData response) {
Toast.makeText(MainActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show(); }
});
requestQueue.add(myGson); }
public class MyGsonRequestextends Request{
private Response.ListenermListener;
private Gson mGson;
private ClassmClass;
public MyGsonRequest(int method, String url, Response.ErrorListener listener, Classcls,
Response.ListenersucessList) {
super(method, url, listener);
this.mListener = sucessList;
this.mClass = cls;
mGson = new Gson(); }
//自定义Request //网络处理
@Override
protected ResponseparseNetworkResponse(NetworkResponse response) {
String jsonStr;
try {
jsonStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
jsonStr = new String(response.data);
}
return Response.success(mGson.fromJson(jsonStr, mClass), HttpHeaderParser.parseCacheHeaders(response));
}
//成功过后
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
网友评论