Okhttp简单封装

一、Okhttp简介
Android为我们提供了两种HTTP交互的方式: HttpURLConnection 和 Apache HTTP Client,虽然两者都支持
HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用
HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。

OkHttp是一个高效的HTTP库:
1.支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
2.如果SPDY不可用,则通过连接池来减少请求延时
3.无缝的支持GZIP来减少数据流量
4. 缓存响应数据来减少重复的网络请求

OkHttp会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,
会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
使用 OkHttp无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您
用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。

二、Okhttp用法
1、Get 请求

Okhttp简单封装_第1张图片
Paste_Image.png
OkHttpClient 客户端对象
Request是OkHttp中访问的请求,
Builder是辅助类。
Response即OkHttp中的响应。

2、Http POST (JSON)

Okhttp简单封装_第2张图片
Paste_Image.png
MediaType 数据类型
RequestBody 请求数据

3、Http POST (FormData)

Okhttp简单封装_第3张图片
Paste_Image.png
FormEncodingBuilder 表单构造器

三、Okhttp的简单封装
OkHttpHelper.java

public class OkHttpHelper {


    public static final int TOKEN_MISSING=401;// token 丢失
    public static final int TOKEN_ERROR=402; // token 错误
    public static final int TOKEN_EXPIRE=403; // token 过期



        public static final String TAG="OkHttpHelper";

        private  static  OkHttpHelper mInstance;
        private OkHttpClient mHttpClient;
        private Gson mGson;

        private Handler mHandler;



        static {
            mInstance = new OkHttpHelper();
        }

        private OkHttpHelper(){

            mHttpClient = new OkHttpClient();
            mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
            mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
            mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);

            mGson = new Gson();

            mHandler = new Handler(Looper.getMainLooper());

        };

        public static  OkHttpHelper getInstance(){
            return  mInstance;
        }




        public void get(String url,Map param,BaseCallback callback){


            Request request = buildGetRequest(url,param);

            request(request,callback);

        }

        public void get(String url,BaseCallback callback){

            get(url,null,callback);
        }


        public void post(String url,Map param, BaseCallback callback){

            Request request = buildPostRequest(url,param);
            request(request,callback);
        }





        public  void request(final Request request,final  BaseCallback callback){

            callback.onBeforeRequest(request);

            mHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Request request, IOException e) {
                    callbackFailure(callback, request, e);

                }

                @Override
                public void onResponse(Response response) throws IOException {

//                    callback.onResponse(response);
                    callbackResponse(callback,response);

                    if(response.isSuccessful()) {

                        String resultStr = response.body().string();

                        Log.d(TAG, "result=" + resultStr);

                        if (callback.mType == String.class){
                            callbackSuccess(callback,response,resultStr);
                        }
                        else {
                            try {

                                Object obj = mGson.fromJson(resultStr, callback.mType);
                                callbackSuccess(callback,response,obj);
                            }
                            catch (com.google.gson.JsonParseException e){ // Json解析的错误
                                callback.onError(response,response.code(),e);
                            }
                        }
                    }
                    else if(response.code() == TOKEN_ERROR||response.code() == TOKEN_EXPIRE ||response.code() == TOKEN_MISSING ){

                        callbackTokenError(callback,response);
                    }


                    else {
                        callbackError(callback,response,null);
                    }

                }
            });


        }


    private void callbackTokenError(final  BaseCallback callback , final Response response ){

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callback.onTokenError(response,response.code());
            }
        });
    }

        private void callbackSuccess(final  BaseCallback callback , final Response response, final Object obj ){

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onSuccess(response, obj);
                }
            });
        }


        private void callbackError(final  BaseCallback callback , final Response response, final Exception e ){

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onError(response,response.code(),e);
                }
            });
        }



    private void callbackFailure(final  BaseCallback callback , final Request request, final IOException e ){

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callback.onFailure(request,e);
            }
        });
    }


    private void callbackResponse(final  BaseCallback callback , final Response response ){

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callback.onResponse(response);
            }
        });
    }



    private  Request buildPostRequest(String url,Map params){

            return  buildRequest(url,HttpMethodType.POST,params);
        }

        private  Request buildGetRequest(String url,Map param){

            return  buildRequest(url,HttpMethodType.GET,param);
        }

        private  Request buildRequest(String url,HttpMethodType methodType,Map params){


            Request.Builder builder = new Request.Builder()
                    .url(url);

            if (methodType == HttpMethodType.POST){
                RequestBody body = builderFormData(params);
                builder.post(body);
            }
            else if(methodType == HttpMethodType.GET){

                url = buildUrlParams(url,params);
                builder.url(url);

                builder.get();
            }


            return builder.build();
        }



    private   String buildUrlParams(String url ,Map params) {

        if(params == null)
            params = new HashMap<>(1);

        String token = CniaoApplication.getInstance().getToken();
        if(!TextUtils.isEmpty(token))
            params.put("token",token);


        StringBuffer sb = new StringBuffer();
        for (Map.Entry entry : params.entrySet()) {
            sb.append(entry.getKey() + "=" + (entry.getValue()==null?"":entry.getValue().toString()));
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }

        if(url.indexOf("?")>0){
            url = url +"&"+s;
        }else{
            url = url +"?"+s;
        }

        return url;
    }

        private RequestBody builderFormData(Map params){
            FormEncodingBuilder builder = new FormEncodingBuilder();

            if(params !=null){

                for (Map.Entry entry :params.entrySet() ){
                    builder.add(entry.getKey(),entry.getValue()==null?"":entry.getValue().toString());
                }

                String token = CniaoApplication.getInstance().getToken();
                if(!TextUtils.isEmpty(token))
                    builder.add("token", token);
            }

            return  builder.build();

        }

        enum  HttpMethodType{
            GET,
            POST,
        }
}

BaseCallback.java

public abstract class BaseCallback  {


    public   Type mType;

    static Type getSuperclassTypeParameter(Class subclass)
    {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class)
        {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    }


    public BaseCallback()
    {
        mType = getSuperclassTypeParameter(getClass());
    }



    public  abstract void onBeforeRequest(Request request);


    public abstract  void onFailure(Request request, Exception e) ;


    /**
     *请求成功时调用此方法
     * @param response
     */
    public abstract  void onResponse(Response response);

    /**
     *
     * 状态码大于200,小于300 时调用此方法
     * @param response
     * @param t
     * @throws IOException
     */
    public abstract void onSuccess(Response response,T t) ;

    /**
     * 状态码400,404,403,500等时调用此方法
     * @param response
     * @param code
     * @param e
     */
    public abstract void onError(Response response, int code,Exception e) ;

    /**
     * Token 验证失败。状态码401,402,403 等时调用此方法
     * @param response
     * @param code

     */
    public abstract void onTokenError(Response response, int code);

}

SimpleCallback.java(处理Token的CallBack)

public abstract class SimpleCallback extends BaseCallback {

    protected Context mContext;

    public SimpleCallback(Context context){

        mContext = context;

    }

    @Override
    public void onBeforeRequest(Request request) {

    }

    @Override
    public void onFailure(Request request, Exception e) {

    }

    @Override
    public void onResponse(Response response) {

    }

    @Override
    public void onTokenError(Response response, int code) {
        ToastUtils.show(mContext, mContext.getString(R.string.token_error));

        Intent intent = new Intent();
        intent.setClass(mContext, LoginActivity.class);
        mContext.startActivity(intent);

        mApplication.getInstance().clearUser();

    }
}

SpotsCallBack.java(包含加载框的CallBack)

public abstract class SpotsCallBack extends SimpleCallback {



    private  SpotsDialog mDialog;

    public SpotsCallBack(Context context){
        super(context);

        initSpotsDialog();
    }


    private  void initSpotsDialog(){

        mDialog = new SpotsDialog(mContext,"拼命加载中...");
    }

    public  void showDialog(){
        mDialog.show();
    }

    public  void dismissDialog(){
        mDialog.dismiss();
    }


    public void setLoadMessage(int resId){
        mDialog.setMessage(mContext.getString(resId));
    }


    @Override
    public void onBeforeRequest(Request request) {

        showDialog();
    }

    @Override
    public void onResponse(Response response) {
        dismissDialog();
    }


}

你可能感兴趣的:(Okhttp简单封装)