网络第三方框架有xutil、xutil3、volle以及okhttp 和okhttp衍生出来的一大批壳外的壳
那么既然已经有了那么多优秀的产品为什么还要自己封装呢,有以下两个原因:
1.引入retrofit、 noHttp 等增加了很多不必要的代码,增大了apk 包(第三方引用的会被keep)
2.使用retrofit、 noHttp等会对程序的可扩展性产生重大隐患
3.适合自己项目的才是好方案,合理的中间层处理会大大降低程序的代码量和开销
下面将从代码角度分析如何封装适合自己的网络框架
本文仅适合具备较强学习能力的开发者阅读,因为此文的目的在于提供思路和简单的使用场景,为达到适合自己的网络框架需求需要自己对中间层根据范例进行处理,对合适的modle进行编写。
在此之前你需要具备以下基础技能点:
接口回调、泛型、线程
一、使用场景
获取Person 对象,onSucess、onFaild回调在主线程
public void getPerson(){
HashMapparams=new HashMap();
params.put("type","1");
HttpRequest.postRequest(context, "http://test/person", params,
new ModleRequest(Person.class) {
@Override
protected void onSucess(Person person) {}
@Override
protected void onFaild(Exception e) { }
});
}
二、入口程序
import java.io.File;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import cnn.customer.utils.net.action.DownLoad;
import cnn.customer.utils.net.action.GetRequest;
import cnn.customer.utils.net.action.PostRequest;
import cnn.customer.utils.net.action.UploadRequest;
import cnn.customer.utils.net.inter.BaseRequest;
import cnn.customer.utils.net.inter.FileRequest;
import cnn.customer.utils.net.modle.StringRequest;
import okhttp3.OkHttpClient;
/**
* Created by biyunlong on 2016/9/5.
*/
public class HttpRequest {
public static OkHttpClient okHttpClient;
public static void init() {
if (null == okHttpClient) {
OkHttpClient.Builder ClientBuilder = new OkHttpClient.Builder();
ClientBuilder.readTimeout(60, TimeUnit.SECONDS);//读取超时
ClientBuilder.connectTimeout(60, TimeUnit.SECONDS);//连接超时
ClientBuilder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
okHttpClient = ClientBuilder.build();
}
}
public static void getRequest(String url, final BaseRequest re) {
GetRequest.getRequest(url,re,okHttpClient);
}
//普通接口
public static void postRequest(HashMap params, String url, final BaseRequest re) {
PostRequest.postRequest(params,url,re,okHttpClient);
}
//下载文件
public static void downLoad(String url, String path, String name, FileRequest fileRequest){
DownLoad.downLoadFile(url,path,name,okHttpClient,fileRequest);
}
//上传单个图片
public void uploadImage(String url, HashMap params, File file, StringRequest stringRequest){
UploadRequest.upLoadFile(url,params,file,stringRequest,okHttpClient);
}
//上传多张图片
public void uploadMoreImage(String url, HashMap params, HashMap params2, File file, StringRequest stringRequest){
UploadRequest.uploadMoreFile(url,params,params2,stringRequest,okHttpClient);
}
//上传base64图片
public void UploadBase64( String url, HashMap params, String content, final BaseRequest re){
UploadRequest.UploadBase64(url,params,content,re,okHttpClient);
}
}
三、执行程序
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import cnn.customer.utils.net.inter.BaseRequest;
import cnn.customer.utils.net.tools.MainHandler;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* 文件描述:
* 创 建 人:byl
* 创建时间:2017/9/5 0005 18:13
*/
public class PostRequest {
public static void postRequest(HashMap params, String url, final BaseRequest re, OkHttpClient okHttpClient) {
//创建Form表单对象,可以add多个键值队
FormBody.Builder builder = new FormBody.Builder();
if (params != null) {
Iterator> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
builder.add(entry.getKey(), entry.getValue() + "");
}
}
FormBody formBody = builder.build();
//创建一个Request
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
//发送请求获取响应
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
re.baseOnFaild(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
MainHandler.getInstance().post(new Runnable() {
@Override
public void run() {
re.baseOnSucess(str);
}
});
Log.d("debug", str);
}
});
}
}
四、modle中间层
可根据需要自行编写StringRequest 或者ListRequest ,也可以根据泛型指定返回格式,然后通过类型转换(不推荐)
/**
* Created by biyunlong on 2016/9/5.
*/
public abstract class BaseRequest {
public abstract void baseOnSucess(String json);
public abstract void baseOnFaild(Exception e);
}
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.ParameterizedType;
import cnn.customer.utils.net.inter.BaseRequest;
/**
* Created by biyunlong on 2017/5/3.
* Make progress every day
*/
public abstract class BeanRequest extends BaseRequest {
private int status;
private String msg;
@Override
public void baseOnSucess(String jsonstr) {
try {
JSONObject jsonRoot = new JSONObject(jsonstr);
status=jsonRoot.getInt("result");
msg=jsonRoot.getString("message");
if(status==200){
JSONObject jsonResult=jsonRoot.getJSONObject("data");
String strResult=jsonResult.toString();
T t=(T)(new Gson().fromJson(strResult,((ParameterizedType)(getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
onSucess(t,status,msg);
}else{
onSucess(null,status,msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void baseOnFaild(Exception e) {
onFaild(e);
}
public abstract void onSucess(T t,int status,String msg);
public abstract void onFaild(Exception e);
}