自己封装了一个okhttp,使用起来比较简单,可以处理https,所有的请求一个方法搞定,包括get,post,键值对传输,json传输,文件上传下载等等。。
compile 'com.github.hl:MyOkHttp:1.0.0'
就这一句话
首先在Application 里面加入
HttpClientUtils.getInstance().setTimeOut(20) //设置连接时间
.setTimeRead(30) //设置读取时间
.setTimeUnit(TimeUnit.SECONDS) //设置时间类型,时分秒。。
.setISCertificates(null) //证书的inputstream
.setISBksFile(null) //本地证书的inputstream
.setPassWord(null) //本地证书的密码
.setDebug(true) //是否打印log
.init(this);
若是嫌麻烦,并且没有证书,直接HttpClientUtils.getInstance().init(this) 就好了,参数都是有默认值,默认是就是我上面写的
配置完了 就是使用了
首先是post方法,键值对传输,举个例子
写个AdddepartmentRequest.class继承BaseRequest ,在里面写好你所需要传的参数,顺便get,set一下,在fetchUrl 里面写上返回url,这样,传入的参数就全部写好了
再写个接受返回数据的方法继承BaseResponse
里面写接受返回的参数,顺便get set 一下,这里可以直接用Gsonformat插件,简单快捷
要注意的是,里面所有的类一定要序列化一下,特别是子类,不然测试没问题,正式打包会没数据
像这样
传参跟接受数据都处理好了,再写一个通用的接口请求类
package com.android.lynn.dingniu.okhttp;
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
//=====`-.____`-.___\_____/___.-`____.-'======
// `=---='
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// 佛祖保佑 永无BUG
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.huangl.myokhttp.BaseRequest;
import com.android.huangl.myokhttp.BaseResponse;
import com.android.huangl.myokhttp.CallbackInterface;
import com.android.huangl.myokhttp.ClientInterface;
import com.android.huangl.myokhttp.HttpClientUtils;
import com.android.huangl.myokhttp.HttpRequestCallback;
import com.android.huangl.myokhttp.ProgressListener;
import com.android.lynn.dingniu.debug.Logger;
import com.android.lynn.dingniu.okhttp.response.CommonResponse;
import com.android.lynn.dingniu.utils.RSAUtil;
import com.android.lynn.dingniu.utils.SPUtils;
import com.android.lynn.dingniu.utils.Utils;
import com.android.lynn.dingniu.view.dialog.LoadingDialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import static com.android.lynn.dingniu.constant.ConstantOther.KEY_TOKEN;
/**
* 类说明:
*/
public class ClientInterfaceImp implements ClientInterface {
private volatile static ClientInterface anInterface;
public static ClientInterface getInstance() {
if (anInterface == null) {
synchronized (ClientInterfaceImp.class) {
if (anInterface == null)
anInterface = new ClientInterfaceImp();
}
}
return anInterface;
}
/**
* 表单形式
*
* @param context
* @param request 参数
* @param res 返回数据
* @param files 文件
* @param listening 上传监听
* @param TYPE 回调标识
* @param isDialog 弹出层
* @param describe 描述
* @param mHandler
*/
@Override
public void upload(final Context context, final BaseRequest request, final BaseResponse res, final HashMap<String, File[]> files,
final ProgressListener listening, final int TYPE, final boolean isDialog, final String describe, final Handler mHandler) {
final HttpRequestCallback callback = new HttpRequestCallback();
setHeader(context, callback);
Map map = JSON.parseObject(JSONObject.toJSONString(request), Map.class); //将request转化为object,再转为map
callback.enqueue(getClient(), request.method(), request.fetchUrl(), map, describe + " ", files, listening, new CallbackInterface() {
@Override
public void onStart() {
//请求开始
}
@Override
public void onFailure(Call call, IOException e) {
请求失败//
Message msg = mHandler.obtainMessage(TYPE);
if (context != null && !((Activity) context).isFinishing()) {
mHandler.sendMessage(msg);
}
e.printStackTrace();
}
@Override
public void onSuccess(Call call, final Response response) throws IOException {
//请求成功
Message msg = mHandler.obtainMessage(TYPE);
String body = response.body().string();
Logger.getLogger().d(describe + "请求成功>> " + body);
try {
msg.obj = res.parse(body);
} catch (Exception e) {
e.printStackTrace();
}
if (context != null && !((Activity) context).isFinishing()) {
msg.sendToTarget();
}
}
@Override
public void onFinish() {
//请求完成
if (isDialog && context != null && !((Activity) context).isFinishing())
LoadingDialog.dismiss();
}
});
}
/**
* json形式
*
* @param context
* @param request 参数
* @param res 返回数据
* @param TYPE 回调标识
* @param isDialog 弹出层
* @param describe 描述
* @param mHandler
*/
@Override
public void uploadJson(final Context context, final BaseRequest request, final BaseResponse res, final int TYPE, final boolean isDialog,
final String describe, final Handler mHandler) {
HttpRequestCallback callback = new HttpRequestCallback();
callback.enqueueJson(getClient(), request.fetchUrl(), JSONObject.toJSONString(request), describe, new CallbackInterface() {
@Override
public void onStart() {
if (isDialog && context != null && !((Activity) context).isFinishing())
LoadingDialog.createLoadingDialog(context);
}
@Override
public void onFailure(Call call, IOException e) {
Message msg = mHandler.obtainMessage(TYPE);
if (context != null && !((Activity) context).isFinishing()) {
mHandler.sendMessage(msg);
}
e.printStackTrace();
}
@Override
public void onSuccess(Call call, final Response response) throws IOException {
Message msg = mHandler.obtainMessage(TYPE);
String body = response.body().string();
Logger.getLogger().d(describe + "请求成功>> " + body);
try {
msg.obj = res.parse(body);
} catch (Exception e) {
msg.obj = splice(res, CODE_DATA_ERROR, describe + "数据格式错误");
}
if (context != null && !((Activity) context).isFinishing()) {
mHandler.sendMessage(msg);
}
}
@Override
public void onFinish() {
if (isDialog && context != null && !((Activity) context).isFinishing())
LoadingDialog.dismiss();
}
});
}
/**
* @param context
* @param request 参数
* @param res 返回数据
* @param TYPE 回调标识
* @param isDialog 弹出层
* @param describe 描述
* @param FileName 文件名字
* @param mHandler
*/
@Override
public void dowload(final Context context, BaseRequest request, final BaseResponse res, final int TYPE, final boolean isDialog,
final String describe, final String FileName, final Handler mHandler) {
final HttpRequestCallback callback = new HttpRequestCallback();
Map map = JSON.parseObject(JSONObject.toJSONString(request), Map.class); //将request转化为object,再转为map
callback.enqueue(getClient(), request.method(), request.fetchUrl(), map, describe, null, null, new CallbackInterface() {
@Override
public void onStart() {
if (isDialog && context != null && !((Activity) context).isFinishing())
LoadingDialog.createLoadingDialog(context);
}
@Override
public void onFailure(Call call, IOException e) {
Message msg = mHandler.obtainMessage(TYPE);
if (context != null && !((Activity) context).isFinishing()) {
mHandler.sendMessage(msg);
}
e.printStackTrace();
}
@Override
public void onSuccess(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
Message msg = mHandler.obtainMessage(TYPE);
long sum = 0;
long total = response.body().contentLength();
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(FileName), false);
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
sum += len;
fileOutputStream.write(buffer, 0, len);
int progress = (int) (sum * 100.0f / total);
Logger.getLogger().d("文件下载进度>" + progress);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (context != null && !((Activity) context).isFinishing()) {
msg.sendToTarget();
}
} else {
throw new IOException("Unexpected code " + response);
}
}
@Override
public void onFinish() {
if (isDialog && context != null && !((Activity) context).isFinishing())
LoadingDialog.dismiss();
}
}
);
}
/**
* 设置公共头部参数
*
* @param callback
*/
private void setHeader(Context context, HttpRequestCallback callback) {
callback.addHeader("DeviceId", Utils.getIMEI(context));
callback.addHeader("AppVersion", Utils.getVerName(context) + "");
callback.addHeader("DeviceVersion", Utils.getSystemVersion());
callback.addHeader("DeviceModel", Utils.getSystemModel());
}
/**
* 获取okHttpClient
*
* @return
*/
private OkHttpClient getClient() {
return HttpClientUtils.getInstance().getOkHttpClient();
}
}
这个 upload方法用于键值对传输,uploadJson用于json传输,需要哪个就写哪个就好,每个参数的意思已经写在上面了,通俗易懂,json传输不能传递文件,因为json传输最终是在头信息里面传输的,那个isDialog,我上面写是否弹出弹出层,这只是一种逻辑,可以改成别的,就是一个判断而已,不需要可以忽略。setHeader 就是添加头信息的
这样,公共请求方式写完了
最后来调用,
AdddepartmentRequest里面把参数值放进去,upload方法填写好参数,这个没有文件上传,所以文件参数全部填null,type用来标识,handle处理返回数据 注意,post方法必须要输入至少一个参数
private MyHandler mHandler;
private class MyHandler extends Handler {
WeakReference<Activity> mWeakReference;
public MyHandler(Activity activity) {
mWeakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1: //添加部门
DepartmentModel s1 = (DepartmentModel) msg.obj;
if (s1.getCode() == 200) {
//处理逻辑
} else {
Utils.showToast(mWeakReference.get(), s1.getMsg());
}
break;
case 2: //删除部门
CommonResponse s2 = (CommonResponse) msg.obj;
if (s2.getCode() == 200) {
//处理逻辑
} else {
Utils.showToast(mWeakReference.get(), s2.getMsg());
}
break;
default:
break;
}
}
}
记得 handler初始化一下 mhandler = new MyHandler(this),
这样 就全部写好了
如果要上传文件,直接这样就好
/**
* 单文件上传
*
* @param path
*/
private void upload(String path) {
BaseRequest request = new BaseRequest(url_Upload);
ClientInterface mn = ClientInterfaceImp.getInstance();
HashMap<String, File[]> mapFile = null;
//往mapFile里面添加数据
mn.upload(this, request, new FtpResModel(), ((mapFile != null) ? mapFile : null), null, 0, true, "单文件上传", mHandler);
}
mapFile里面放文件数据,value是个File数组,可以上传多个文件,文件上传是单个上传的,upload里面的listening参数自己可以new一个,用来显示上传数据的进度
这样 文件上传也搞定了
说下get方法,更简单不过
BaseRequest request = new BaseRequest(url_LoginCompany + "?companyId=" + companyId);
request.setMethod(false);
ClientInterface mn = ClientInterfaceImp.getInstance();
mn.upload(getActivity(), request, new LoginCompanyInfoResModel(), null, null, 0, b, "测试", mHandler);
在BaseRequest里面填入url,再设置 setMethod(false)就可以了
至于文件下载,方法一样,mn.dowload(....),这里的处理方法我是直接写在ClientInterfacImp里面,可以直接引出来写在想这的地方
这样,这个框架就全部介绍完了