Android项目开发中网络请求几乎是不可避免的,之前项目经常用到volley网络请求库,不做封装的话每次有新的项目都需要每个请求的去写,容易出问题,并且复用性不清,所以后来花时间重新整理了一下,对volley库进行了二次封装,封装出了自己需要用的常用方法,后面有新项目需要使用的话直接使用这个封装的公共库就行,大大提高了开发效率。
先分享一下,当然肯定还有需要修改优化的地方,目前自用基本够用。也欢迎大家提出修改优化建议
```
public class NetUtil {
protected static final String TAG = "NetUtil";
public static RequestQueue queue;
public final static int TIME_OUT_NORMAL = 30 * 1000;
public final static int RETRY_TIME = 0;
public static final int GET = Method.GET;
public static final int POST = Method.POST;
public static final int PUT = Method.PUT;
public static final int DELETE = Method.DELETE;
/**
* 回调接口
*/
public interface NetListenerT {
<T> void onResponse(T t);
}
/**
* 异常回调接口
**/
public interface NetListenerError {
void onErrorResponse(String error);
}
/**
* 网络请求(POST、GET)
*/
public static <T> void requestSimple(final int MethodType, String url, final Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
addUserInfo(params);
if (MethodType == GET) {
url = URLBuilder(url, params);
LogUtil.i(TAG, url);
}
final String finalUrl = url;
StringRequest mRequest = new StringRequest(MethodType, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
LogUtil.i(TAG, response);
T t = GsonUtil.json2bean(response, jBean);
if (t == null) {
LogUtil.e(TAG, "JSON解析错误");
}
// 回调
listener.onResponse(t);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error != null && error.networkResponse != null && error.networkResponse.statusCode == 401) {
//权限验证失败,退出登录
} else {
if (listenerError != null) {
listenerError.onErrorResponse(error.getMessage());
}
LogUtil.e(TAG, "调用接口出错:" + finalUrl);
LogUtil.e(TAG, error + "");
}
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
if (MethodType == POST) {
return getUserParams(params);
} else {
return null;
}
}
};
mRequest.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT_NORMAL, RETRY_TIME, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mRequest);
}
/**
* 网络请求(POST、GET)
*/
public static <T> void requestJsonSimple(final int MethodType, String url, final Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
addUserInfo(params);
if (MethodType == GET) {
url = URLBuilder(url, params);
LogUtil.i(TAG, url);
} else {
Map<String, String> tmpparams = new HashMap<>();
tmpparams.put(Constant.KEY_TOKEN, params.get(Constant.KEY_TOKEN));
url = URLBuilder(url, tmpparams);
}
final String finalUrl = url;
StringRequest mRequest = new StringRequest(MethodType, url, new Response.Listener<String>() {
@Override
public void onResponse(String jsonObject) {
T t = GsonUtil.json2bean(jsonObject.toString(), jBean);
if (t == null) {
LogUtil.e(TAG, "JSON解析错误");
}
// 回调
listener.onResponse(t);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error != null && error.networkResponse != null && error.networkResponse.statusCode == 401) {
//权限验证失败
} else {
if (listenerError != null) {
listenerError.onErrorResponse(error.getMessage());
}
LogUtil.e(TAG, "调用接口出错:" + finalUrl);
LogUtil.e(TAG, error + "");
}
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
return params.get("json").toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
mRequest.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT_NORMAL, RETRY_TIME, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mRequest);
}
/**
* 网络请求(POST、GET)
*/
public static <T extends Base> void request(final Activity acivity, final int MethodType, String url, final Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
if (!url.contains(!url.contains(NetURL.URL_LOGIN)) {
if(MethodType==GET) {
addUserInfo(params);
}
}
if (acivity == null) {
return;
}
if (MethodType == GET) {
url = URLBuilder(url, params);
LogUtil.i(TAG, url);
}
final String finalUrl = url;
StringRequest mRequest = new StringRequest(MethodType, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (acivity == null || !EgovaApplication.isRunning(acivity) || acivity.isFinishing()) {
return;
}
LogUtil.i(TAG, response);
T t = GsonUtil.json2bean(response, jBean);
if (t == null) {
LogUtil.e(TAG, "JSON解析错误");
}
if (t == null || (!t.login && t.error_id!=0)) {
Intent intent = new Intent(acivity, LoginActivity.class);
if(t!=null && t.error_id>0){
intent.putExtra("message", t.description);
}else {
if (t == null || StringUtil.isNull(t.message)) {
intent.putExtra("message", "JSON解析错误");
} else {
intent.putExtra("message", t.message);
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
acivity.startActivity(intent);
acivity.finish();
} else {
// 回调
listener.onResponse(t);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error != null && error.networkResponse != null && error.networkResponse.statusCode == 401) {
//权限验证失败,退出登录
} else {
if (listenerError != null) {
if (!StringUtil.isNull(error.getMessage())) {
listenerError.onErrorResponse(error.getMessage());
} else {
listenerError.onErrorResponse("请求异常,请确认网络连接是否正常");
}
}
LogUtil.e(TAG, "调用接口出错:" + finalUrl);
LogUtil.e(TAG, error + "");
}
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
if (MethodType == POST || MethodType==PUT) {
return getUserParams(params);
} else {
return null;
}
}
};
mRequest.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT_NORMAL, RETRY_TIME, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequest.setTag(acivity.getClass().getSimpleName());
queue.add(mRequest);
}
/**
* 网络请求(默认GET)
*/
public static <T> void requestSM(String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
requestSimple(GET, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(默认POST)
*/
public static <T> void postSM(String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
requestSimple(POST, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(默认PUT)
*/
public static <T> void putSM(String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
requestSimple(PUT, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(默认POST)
*/
public static <T> void postJsonSM(String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
requestJsonSimple(POST, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(默认GET)
*/
public static <T> void requestJsonSM(String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
requestJsonSimple(GET, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(默认GET)
*/
public static <T> void putJsonSM(String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
requestJsonSimple(PUT, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(默认GET)
*/
public static <T extends Base> void request(Activity activity, String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
request(activity, GET, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(POST)
*/
public static <T extends Base> void post(Activity activity, String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
request(activity, POST, url, params, jBean, listener, listenerError);
}
/**
* 网络请求(POST)
*/
public static <T extends Base> void put(Activity activity, String url, Map<String, String> params, final Class<T> jBean, final NetListenerT listener, final NetListenerError listenerError) {
request(activity, PUT, url, params, jBean, listener, listenerError);
}
/**
* 取消网络请求
*/
public static void cancel(String tag) {
if (!StringUtils.isEmpty(tag)) {
queue.cancelAll(tag);
}
}
/**
* 在post的情况,为params加userID和password参数
*
* @param params 参数列表
*/
protected static Map<String, String> getUserParams(Map<String, String> params) {
if(UserConfig.getBKeyValue(Constant.KEY_IS_LOGIN, false)) {
if (params != null) {
if (!params.containsKey(Constant.KEY_TOKEN)) {
try {
params.put(Constant.KEY_TOKEN, URLEncoder.encode(UserConfig.getToken(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
params.put(Constant.KEY_TOKEN, UserConfig.getToken());
}
}
}
}
return params;
}
/**
* 为url添加user参数
*/
private static String addUserInfo(String url) {
if (UserConfig.getBKeyValue(Constant.SP_KEY_IS_LOGIN, false)) {
//登录状态下要添加token
if (UserConfig.getToken() != null && !UserConfig.getToken().equals("")) {
if (!url.contains(Constant.KEY_TOKEN)) {
try {
url += "&" + Constant.KEY_TOKEN + "=" + URLEncoder.encode(UserConfig.getToken(), "UTF-8");
} catch (UnsupportedEncodingException e) {
LogUtil.e(TAG, e.getMessage());
}
}
}
}
return url;
}
/**
* 构造URL
*
* @param url 请求url
* @param params 请求参数
*/
private static String URLBuilder(String url, Map<String, String> params) {
/* List<NameValuePair> valueParams = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
valueParams.add(new BasicNameValuePair(key, params.get(key).toString()));
}
return url + "?" + URLEncodedUtils.format(valueParams, "UTF-8");*/
String newUrl = url;
StringBuffer param = new StringBuffer();
for (String key : params.keySet()) {
param.append(key + "=" + params.get(key) + "&");
}
String paramStr = param.toString();
paramStr = paramStr.substring(0, paramStr.length() - 1);
if (newUrl.indexOf("?") >= 0) {
newUrl += "&" + paramStr;
} else {
newUrl += "?" + paramStr;
}
return newUrl;
}
/**
* 为url添加用户user参数
*/
private static void addUserInfo(Map<String, String> params) {
if (params != null && UserConfig.getBKeyValue(Constant.KEY_IS_LOGIN, false)) {
if (!params.containsKey(Constant.KEY_TOKEN)) {
try {
params.put(Constant.KEY_TOKEN, URLEncoder.encode(UserConfig.getToken(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
params.put(Constant.KEY_TOKEN, UserConfig.getToken());
}
}
}
}
/**
* 为url添加用户user参数
*/
private static void addUserInfo(JSONObject params) {
if (params != null && UserConfig.getBKeyValue(Constant.KEY_IS_LOGIN, false)) {
try {
if (!params.has(Constant.KEY_TOKEN)) {
params.put(Constant.KEY_TOKEN, UserConfig.getToken());
}
}catch (Exception ex){
LogUtil.e(TAG, ex.getMessage());
}
}
}
}
```