对okhttp、okio进行二次封装:
(非完整代码,只包含完整思路)
**
* 网络操作类
*/
public class HttpBase {
public static String push_token = "";
private RequestQueue queue = null;// 请求队列
private Context context;
private AsyncHttpClient asyncHttpclient;
public HttpBase(Context context) {
super();
queue = Volley.newRequestQueue(context);// 创建一个新的队列
this.context = context;
asyncHttpclient = new AsyncHttpClient();
}
/**
* 队列停止工作
*/
public void stopQueue() {
if (queue != null) {
queue.stop();
}
}
/**
* 获得jsonObject
*
* @param method 方法
* @param url 路劲
* @param list 参数列表
* @param hasPath List 中是否包含路径的KeyValue
* @param listener 监听器
*/
void doGetEntityConnect(int method, String url, List<MyKeyValues> list,
boolean hasPath, final JsonObjectListener listener) {
JSONObject json = null;
LogUtils.e(getClass().getName(), " url :" + url);
try {
json = JSONUtil.List2Json(list);
if (hasPath)
json = file_direction_repair(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
LogUtils.e(getClass().getName(), "请求的json:" + json + "\n url :" + url);
// 联网之前判断一下是否有网络
if (!NetworkValue.isNetWorkEnable()) {
listener.OnFailure(new ErrorReson(-4, context.getResources()
.getString(R.string.str_check_network)));
return;
}
JsonObjectRequest request = new JsonObjectRequest(method, url, json,
new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
LogUtils.e(getClass().getName(), "response:" + response);
listener.OnSuccess(response);
int code;
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
LogUtils.e(getClass().getSimpleName(), "失败");
LogUtils.e("VOLLEY", error.toString());
listener.OnFailure(new ErrorReson(-2, "服务器连接失败"));
}
});
// request.setTag(tag);
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
queue.add(request);
}
/**
* 使用form的请求数据
*/
void doGetForm(String url, List<MyKeyValues> list,
final JsonObjectListener listener) {
// 联网之前判断一下是否有网络
if (!NetworkValue.isNetWorkEnable()) {
if (listener!=null)
listener.OnFailure(new ErrorReson(-4, context.getResources()
.getString(R.string.str_check_network)));
return;
}
RequestParams rParams = List2Parms(list);
LogUtils.e(getClass().getName(), " url :" + url);
LogUtils.e(getClass().getName(), "请求的Form:" + rParams.toString() + "\n url :" + url);
asyncHttpclient.post(url,
rParams, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
String json = new String(bytes);
LogUtils.e(getClass().getName(), "response:" + json);
try {
JSONObject jsonObject = new JSONObject(json);
if (listener!=null)
listener.OnSuccess(new JSONObject(json));
} catch (JSONException e) {
if (listener!=null)
listener.OnFailure(new ErrorReson(-1, "返回结果解析失败"));
e.printStackTrace();
}
}
@Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
throwable.printStackTrace();
if (bytes == null || bytes.length == 0) {
if (listener!=null)
listener.OnFailure(new ErrorReson(i, i + ",服务器异常"));
return;
}
String msg = new String(bytes);
String error_message = "";
LogUtils.e("img上传失败 " + i, msg);
try {
JSONObject jsonObject = new JSONObject(msg);
error_message = jsonObject.getString("error_message");
} catch (JSONException e) {
e.printStackTrace();
if (listener!=null)
listener.OnFailure(new ErrorReson(i, i + ",服务器异常"));
return;
}
if (listener!=null)
listener.OnFailure(new ErrorReson(i, i + "," + error_message + ",数据异常"));
}
});
}
public static RequestParams List2Parms(List<MyKeyValues> list) {
RequestParams rParams = new RequestParams();
for (MyKeyValues keyValues : list) {
if (keyValues.getType() == MyKeyValues.STREAM)
rParams.put(keyValues.getKey(), (InputStream) keyValues.getValue());
else
rParams.put(keyValues.getKey(), keyValues.getValue());
}
return rParams;
}
public void MyDoPostRequest(String url, String json, final JsonObjectListener listener) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, json,
new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
listener.OnSuccess(jsonObject);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
listener.OnFailure(new ErrorReson(500, volleyError.getMessage()));
}
});
queue.add(request);
}
/**
* get方法接口回调
*
* @param url
* @param listener
*/
public void doGetRequest(String url, final JsonObjectListener listener) {
LogUtils.e(getClass().getName(), " url :" + url);
JsonObjectRequest request = new JsonObjectRequest(url,
new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
LogUtils.e(getClass().getName(), "response:" + jsonObject.toString());
if (listener != null) {
listener.OnSuccess(jsonObject);
}
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (listener != null) {
listener.OnFailure(new ErrorReson(500, volleyError.getMessage()));
}
}
});
queue.add(request);
}
/**
* get方法接口回调
*
* @param url
* @param listener
*/
public void doGetNotJson(String url, final SimpleSuccessListener listener) {
LogUtils.e(getClass().getName(), " url: " + url);
Request request = new StringRequest(url,new Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.e(getClass().getName(), "response: " + response);
if (listener != null) {
listener.onSuccess(response);
}
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (listener != null) {
listener.onFailure(new ErrorReson(500, volleyError.getMessage()));
}
}});
queue.add(request);
}
/**
* 处理不成功情况的接口回调
*
* @param code
* @param listener
*/
private void doOnErrorCode(int code, String msg, JsonObjectListener listener) {
listener.OnFailure(new ErrorReson(code, msg));
// switch (code) {
//
// default:
// listener.OnFailure(new ErrorReson(-1, "未知错误"));
// }
}
/**
* 返回得到的json
*
* @author huanghuanPC
*/
public interface JsonObjectListener {
void OnSuccess(JSONObject json);
void OnFailure(ErrorReson reason);
}
/**
* 简单的接口回调
*/
public interface SimpleSuccessListener {
void onSuccess(Object response);
void onFailure(ErrorReson reason);
}
/**
*
*/
public static class ErrorReson {
private int code;
private String msg;
public ErrorReson(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "ErrorReson [code=" + code + ", msg=" + msg + "]";
}
}
/**
* 文件路径调整(可优化)
*
* @param str
* @return
* @throws JSONException
*/
private JSONObject file_direction_repair(String str) throws JSONException {
char[] cha = str.toCharArray();
int j = 0, k = 0;
for (; j < cha.length; j++)
if (cha[j] != '\\')
cha[k++] = cha[j];
str = new String(cha, 0, k);
return new JSONObject(str);
}
/**
* 下载bitmap
*
* @param url
* @param width 图片的最大宽 指定0的话就是不压缩
* @param height 图片的最大高 指定0的话就是不压缩
* @param listener
*/
void doGetBitmap(String url, int width, int height,
final OnEntityConnectListener<Bitmap> listener) {
@SuppressWarnings("deprecation")
ImageRequest request_image = new ImageRequest(url,
new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
listener.OnSuccess(response);
}
}, width, height, Config.ARGB_8888, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.OnFailure(new ErrorReson(-1, "下载图片失败"));
}
});
queue.add(request_image);
}
public void getBitmapFromNet(String url,
final OnEntityConnectListener<Bitmap> listener) {
LogUtils.d("Bitmap Fetch", "URL : " + url);
@SuppressWarnings("deprecation")
ImageRequest imageRequest = new ImageRequest(url,
new Listener<Bitmap>() {
@Override
public void onResponse(Bitmap arg0) {
listener.OnSuccess(arg0);
}
}, 0, 0, Config.RGB_565, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
listener.OnFailure(new ErrorReson(-2, "Request Net Fail"));
}
});
imageRequest.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
queue.add(imageRequest);
}
/**
* 返回实体类的回调接口
*
* @param <T>
*/
public static abstract class OnEntityConnectListener<T> {
/**
* 成功的时候回调该方法
*
* @param entity 联网获得的实体类
*/
public abstract void OnSuccess(T entity);
/**
* 失败的时候回调该接口
*
* @param reason
*/
public void OnFailure(ErrorReson reason) {
}
}
}
一个使用例子
public class HttpUtil {
HttpBase base;
private Context context;
public HttpUtil(Context context) {
super();
base = new HttpBase(context);
this.context = context;
}
/**
* 队列停止工作
*/
public void StopQueue() {
base.stopQueue();
}
private static final int P_VERSION = NetworkValue.P_VERSION;// 协议的版本号
/**
* 登录 post
*
* @param userno
* @param machineid
*/
public void Login(String userno, String machineid, HttpBase.JsonObjectListener jsonObjectListener) {
String str=StaticValue.getRegistrationID();
List<MyKeyValues> list = new ArrayList<>();
list.add(new MyKeyValues("userno", userno, MyKeyValues.String));
list.add(new MyKeyValues("machineid", machineid, MyKeyValues.String));
if (TextUtils.equals(str,null)|| TextUtils.equals(str,"")){
str= JPushInterface.getRegistrationID(context);
StaticValue.setRegistrationID(str);
Logger.e("推送注册id:", str);
}
list.add(new MyKeyValues("registrationid", str, MyKeyValues.String));
base.doGetForm(NetworkValue.URL.str_login_url, list, jsonObjectListener);
}
}