封装OkHttp网络框架

2017-02-23  本文已影响160人  叶为正

<h1>1.OkHttp的简单使用</h1>

/**
 * 发送一个get请求
 */
public void getRequest() {
    final Request request = new Request.Builder().url("https://www.baidu.com/").build();
    OkHttpClient client = new OkHttpClient();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        /**
         * 也是非UI线程
         * @param call
         * @param response
         * @throws IOException
         */
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String res = response.body().toString();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCookieTextView.setText(res);
                }
            });
        }
    });
}

/**
 * 发送一个post请求
 */
private void postRequest() {
    OkHttpClient client = new OkHttpClient();
    FormBody.Builder formBodyBuild = new FormBody.Builder();
    formBodyBuild.add("mb", "15019115390");
    formBodyBuild.add("pw", "9999999");
    Request request = new Request.Builder().url("www.hao.com")
            .post(formBodyBuild.build()).build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        //非Ui线程
        @Override
        public void onResponse(Call call, Response response) throws IOException {

        }
    });

}

以上如此复杂的Http请求,我们需要将他们封装起来,以便我们使用。

2.通用网络框架封装

我们主要的任务:
封装一个公共的的OkHttpClient
封装通用请求创建类CommnonRequest
封装通用响应解析类JsonCommonRequest

Question:如果我们要发送一个请求,就直接调用我们的CommonOkHttpClient,我们调用post请求,只要填写url、参数和回调即可,所以封装如下

CommonOkHttpClient.post(url,params,new DisposeDataListener(){
//请求成功
onSuccess(){

}
//请求失败
onFailed(){

}
})

2.1创建相应的包结构

2.2创建相应的类

1.OkHttpException

是自定义异常类,返回ecode,emsg到业务层,用来快速定位我们OkHttp发出来的异常

public class OkHttpException extends Exception {
    private static final long seriaVersionUID = 1L;

    private int ecode;
    private Object emsg;

    public OkHttpException(int ecode, Object emsg) {
        this.ecode = ecode;
        this.emsg = emsg;
    }

    public int getEcode() {
        return ecode;
    }

    public Object getEmsg() {
        return emsg;
    }

}

```
######2.HttpsUtils
将证书转化为Https,这个是直接拷贝别的开源项目过来的
>关于Https相关资料参考:http://blog.csdn.net/lmj623565791/article/details/48129405

######3.DisposeDataListener响应接口
标明本次请求有哪些回调方法去处理,自定义事件监听
```
public interface DisposeDataListener {
    /**
     * 请求成功回调事件处理
     */
    public void onSuccess(Object responseObj);

    /**
     * 请求失败回调事件处理
     */
    public void onFailure(Object reasonObj);

}
```
######3.DisposeDataHandle
用来处理真正的相应,对json数据的预处理,有如下两种情况
```
public class DisposeDataHandle {
    public DisposeDataListener mListener = null;
    public Class<?> mClass = null;
  
    //1.直接将json抛给应用层处理
    public DisposeDataHandle(DisposeDataListener listener) {
        this.mListener = listener;
    }
      //2.在这里就将json转换成对应的class
    public DisposeDataHandle(DisposeDataListener listener, Class<?> clazz) {
        this.mListener = listener;
        this.mClass = clazz;
    }
}
```
######4.RequestParams
该类存储请求参数,封装所有的请求参数到HashMap中
```
public class RequestParams {

    public ConcurrentHashMap<String, String> urlParams = new ConcurrentHashMap<String, String>();
    public ConcurrentHashMap<String, Object> fileParams = new ConcurrentHashMap<String, Object>();

    /**
     * Constructs a new empty {@code RequestParams} instance.
     */
    public RequestParams() {
        this((Map<String, String>) null);
    }

    /**
     * Constructs a new RequestParams instance containing the key/value string
     * params from the specified map.
     *
     * @param source the source key/value string map to add.
     */
    public RequestParams(Map<String, String> source) {
        if (source != null) {
            for (Map.Entry<String, String> entry : source.entrySet()) {
                put(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Constructs a new RequestParams instance and populate it with a single
     * initial key/value string param.
     *
     * @param key   the key name for the intial param.
     * @param value the value string for the initial param.
     */
    public RequestParams(final String key, final String value) {
        this(new HashMap<String, String>() {
            {
                put(key, value);
            }
        });
    }

    /**
     * Adds a key/value string pair to the request.
     *
     * @param key   the key name for the new param.
     * @param value the value string for the new param.
     */
    public void put(String key, String value) {
        if (key != null && value != null) {
            urlParams.put(key, value);
        }
    }

    public void put(String key, Object object) throws FileNotFoundException {

        if (key != null) {
            fileParams.put(key, object);
        }
    }

    public boolean hasParams() {
        if(urlParams.size() > 0 || fileParams.size() > 0){

            return true;
        }
        return false;
    }

```
######5.CommonRequest
负责创建各种类型的请求对象,包括get,post,文件上传类型
```
public class CommonRequest {
    /**
     * @param url
     * @param params
     * @return 通过传入的参数返回一个Get类型的请求
     */
    public static Request createGetRequest(String url, RequestParams params) {
        StringBuilder urlBuilder = new StringBuilder(url).append("?");
        if (params != null) {
            for (Map.Entry<String, String> entry : params.urlParams.entrySet()) {
                urlBuilder.append(entry.getKey()).append("=")
                        .append(entry.getValue())
                        .append("&");
            }
        }
        return new Request.Builder().url(urlBuilder.substring(0, urlBuilder.length() - 1))
                .get().build();
    }

    /**
     * @param url
     * @param params
     * @return 通过传入的参数返回一个Post类型的请求
     */
    public static Request createPostRequest(String url, RequestParams params) {
        FormBody.Builder mFormBodyBuild = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.urlParams.entrySet()) {
                //将请求参数遍历添加到我们的请求构建类中
                mFormBodyBuild.add(entry.getKey(), entry.getValue());
            }
        }
        //通过请求构件类的build方法获取到真正的请求体对象
        FormBody mFormBody = mFormBodyBuild.build();
        return new Request.Builder().url(url).post(mFormBody).build();
    }

    /**
     * 文件上传
     *
     */
    private static final MediaType FILE_TYPE = MediaType.parse("application/octet-stream");

    public static Request createMultiPostRequest(String url, RequestParams params) {

        MultipartBody.Builder requestBody = new MultipartBody.Builder();
        requestBody.setType(MultipartBody.FORM);
        if (params != null) {

            for (Map.Entry<String, Object> entry : params.fileParams.entrySet()) {
                if (entry.getValue() instanceof File) {
                    requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
                            RequestBody.create(FILE_TYPE, (File) entry.getValue()));
                } else if (entry.getValue() instanceof String) {

                    requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
                            RequestBody.create(null, (String) entry.getValue()));
                }
            }
        }
        return new Request.Builder().url(url).post(requestBody.build()).build();
    }
}
```
上一篇 下一篇

猜你喜欢

热点阅读