首页 > 代码库 > Android 网络请求库volley的封装,让请求更方便

Android 网络请求库volley的封装,让请求更方便

 首先封装一下volley 请求

public class CustomRequest extends StringRequest {

private static final String TAG = CustomRequest.class.getSimpleName();
private String mBody;
private Map<String, String> mHeaders = new HashMap<>();

public CustomRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
     //设置消息头
mHeaders.put("按需求写自己的内容", "按需求写自己的内容");
     mHeaders.put("accetp","application/json");
     //可以有很多个

}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Log.i(TAG, mHeaders.toString());
return mHeaders;
}

@Override
public byte[] getBody() throws AuthFailureError {
try {
return TextUtils.isEmpty(mBody) ? super.getBody() : mBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
// Log.e(TAG, "getBody", e);
}
return super.getBody();
}

public void setBody(String body) {
mBody = body;
}

public Map<String, String> getResonseHeaders() {
return super.getResonseHeaders();
}

}

其次我们还要封装一个请求类

public class CustomRequester<Resp extends Response> {
private static final String TAG = "CustomRequester";
private final Context mContext;
private final Class<Resp> mClazz;
private final com.android.volley.Response.ErrorListener mErrorListener = new com.android.volley.Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError volleyError) {
int statusCode = volleyError == null ? 0 : volleyError.networkResponse == null ? 0 : volleyError.networkResponse.statusCode;
Log.e(TAG, "statusCode: " + statusCode, volleyError);
if (mTag == null) {
return;
}
one rror();
if (statusCode == 0) {
onNetError();
} else if (statusCode == 401) {//不同的请求码做不同的处理
} else if (statusCode == 404) {
} else if (statusCode == 400) {
} else if (statusCode == 403) {

} else {
String json = volleyError.networkResponse.data =http://www.mamicode.com/= null ?"" : new String(volleyError.networkResponse.data);
if (!TextUtils.isEmpty(json)) {
if (mContext instanceof Activity) {
Log.i(TAG, "json " + json);
try {
json = JSON.parseObject(json, Response.class).getMessage();
// one rror(json);
} catch (Exception e) {
one rror(json + "not json format!");
}
}
}
}
}
};

private final com.android.volley.Response.Listener<String> mResponseListener = new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String json) {
Log.i(TAG, "json " + json);
CustomRequester.this.onResponse(json);
if (mTag == null) {
return;
}
try {
final Resp resp = JSON.parseObject(json, mClazz);
if (resp != null) {
onSuccess(resp); //请求成功 这里直接返回解析好的 model
}
} catch (Exception e) {
Log.e(TAG, "onResponse", e);
}
}
};
private String mTag;

public void onResponse(String json) {
}


public void onSuccess(Resp resp) {
}

public void one rror() {
}

public void onNoFoundError() {
if (mContext instanceof Activity) {
}
}

public CustomRequester(Class<Resp> clazz) {
mContext = null;
mClazz = clazz;
}

public CustomRequester(Context context, Class<Resp> clazz) {
mContext = context;
mClazz = clazz;
}

public void cancelAll() {
final String tag = mTag;
mTag = null;
if (!TextUtils.isEmpty(tag)) {
MyApplication.getInstance().getRequestQueue().cancelAll(tag);
}
}

    //Post 请求
public CustomRequest post(String url, int page, String body) {
final RequestQueue queue = MyApplication.getInstance().getRequestQueue();
final CustomRequest request = new CustomRequest(Request.Method.POST, url, mResponseListener, mErrorListener);
try {
final Map<String, String> header = request.getHeaders();
header.remove("Range");
if (page > 0) {
header.put("Range", String.format("page:%1$d,max:10", page));
}
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
mTag = "post," + url + "," + body;
request.setTag(mTag);

Log.i(TAG, mTag);
request.setBody(body);
queue.add(request);
return request;
}
    //Get 请求
public CustomRequest get(String url, int page, String body) {
final RequestQueue queue = YZApplication.getInstance().getRequestQueue();
final CustomRequest request = new CustomRequest(Request.Method.GET, url, mResponseListener, mErrorListener);
try {
final Map<String, String> header = request.getHeaders();
header.remove("Range");
if (page > 0) {
header.put("Range", String.format("page:%1$d,max:10", page));
}
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
mTag = "post," + url + "," + body;
request.setTag(mTag);

Log.i(TAG, mTag);
request.setBody(body);
queue.add(request);
return request;
}
 
    //Put 请求
public CustomRequest put(String url, int page, String body) {
final RequestQueue queue = MyApplication.getInstance().getRequestQueue();
final CustomRequest request = new CustomRequest(Request.Method.PUT, url, mResponseListener, mErrorListener);

try {
final Map<String, String> header = request.getHeaders();
header.remove("Range");
if (page > 0) {
header.put("Range", String.format("page:%1$d,max:10", page));
}
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
mTag = "put," + url + "," + body;
request.setTag(mTag);
request.setBody(body);
queue.add(request);
return request;
}
    //Delete 请求
public CustomRequest delete(String url, int page, String body) {
final RequestQueue queue = MyApplication.getInstance().getRequestQueue();
final CustomRequest request = new CustomRequest(Request.Method.DELETE, url, mResponseListener, mErrorListener);
try {
final Map<String, String> header = request.getHeaders();
header.remove("Range");
if (page > 0) {
header.put("Range", String.format("page:%1$d,max:10", page));
}
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
mTag = "delete," + url + "," + body;
request.setTag(mTag);
request.setBody(body);
queue.add(request);
return request;
}

}
调用
Response是你的model
1.
private AppRequester<Response> mRequester;

2.
mRequester = new AppRequester<Response>(this, Response.class) {
    @Override
public void onSuccess(Response response) {
super.onSuccess(response);
      //成功的操作,展示页面等
}
  
  @Override
  public void one rror() {
   super.onError();
  }
};

3.
//get方式
mRequester.get("URL");
//post 方式  
mRequester.post(URL, JSON.toJSONString(model));
这样就好了,使用时特别方便,你们试试。
 
 

 

Android 网络请求库volley的封装,让请求更方便