OKHttp 网路拦截器 与 okhttp封装

okhttp网络拦截器(自定义)

import java.io.IOException;

        import okhttp3.FormBody;
        import okhttp3.Interceptor;
        import okhttp3.Request;
        import okhttp3.Response;

/**
 * 自定义一个拦截器,每次请求之前携带公共参数
 *
 * 应用层
 *
 */
public class CommonParamsInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        //得到原始的请求对象
        Request request = chain.request();
        //得到用户所使用的请求方式
        String method = request.method();

        if("GET".equals(method)){
            //url
            //原始的请求接口
            String oldUrl = request.url().toString();
         //  重点:可根据需求自定义拼接成一个新的URL
            String newUrl = oldUrl + "要拼接的参数";

            //重新构建请求体
            request = new Request.Builder()
                    .url(newUrl)
                    .build();
        }else if("POST".equals(method)){
            //得到原始的url
            String oldUrl = request.url().toString();
            //得到原有的请求参数
            FormBody oldBody = (FormBody) request.body();//1 2 3
            //新的构建项
            FormBody.Builder builder = new FormBody.Builder();
            for (int i =0 ; i < oldBody.size(); ++i){
                //取出相关请求参数(原有的)
                String name = oldBody.name(i);
                String value = oldBody.value(i);
                //将原始的参数拼装到新的构建体当中
                builder.add(name,value);
            }

            //重点要拼接的数据(post请求)
            builder.add("要拼接的数据","要拼接的数据");

            request = new Request.Builder()
                    .url(oldUrl)
                    .post(builder.build())
                    .build();
        }
        //重新发送请求
        return chain.proceed(request);
    }
}

2.okhttp封装实现单例模式类的名字可选 (OkHttpUtils)

 /**
     * Get请求

     *
     */

   //实现单例模式
    private static OkHttpUtils OK_HTTP_UTILS = null;
    //定义一个Handler
    private static Handler handler = new Handler();

    private OkHttpUtils() {
    }
    /**
     * 得到OkHttpUtils实例对象
     */
    public static OkHttpUtils getInstance() {

        if (null == OK_HTTP_UTILS) {
            synchronized (OkHttpUtils.class) {
                if (null == OK_HTTP_UTILS) {
                    OK_HTTP_UTILS = new OkHttpUtils();
                }
            }
        }
        return OK_HTTP_UTILS;
    }


    public void doGet(String path,Map map,final OnFinishListener onFinishListener) {

        //Http:/www.baidu.com?key=ddd&
        StringBuffer sb = new StringBuffer();
        sb.append(path);
        //判断path是否包含一个
        if(sb.indexOf("?") != -1){

            //判断"?"是否在最后一个
            if(sb.indexOf("?") != sb.length() -1){
                sb.append("&");
            }

        }else{
            sb.append("?");
        }

        //遍历map集合中所有请求参数
        for (Map.Entry entry: map.entrySet()){
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        //判断get请求路径最后是否包含一个"&"
        if(sb.lastIndexOf("&") != -1){
            sb.deleteCharAt(sb.length() - 1);
        }


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //添加应用拦截器
                .addInterceptor(new CommonParamsInterceptor())
                //.addNetworkInterceptor() //添加网络拦截器
                .build();

        //构建请求项
        Request request = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();

        Call call = okHttpClient.newCall(request);
        //execute 子线程  enqueue //
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                //请求失败

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });


            }

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

                //得到服务器的响应结果
                final String result = response.body().string();

                //请求成功
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //主线程当中执行
                        onFinishListener.onSuccess(result);
                    }
                });
            }
        });       
    /**
     * post请求
     *
     * @param path
     * @param map
     * @param onFinishListener
     */
    public void doPost(String path, Map map, final OnFinishListener onFinishListener) {


        OkHttpClient okHttpClient = new OkHttpClient();

        //构建参数的对象
        FormBody.Builder builder = new FormBody.Builder();

        //遍历map集合,获取用户的key/value
        for (String key : map.keySet()) {
            builder.add(key, map.get(key));
        }

        /*FormBody body = new FormBody.Builder()
                .add("mobile",mobile)
                .add("password",password)
                .build();*/
        //构建请求项
        final Request request = new Request.Builder()
                .post(builder.build())
                .url(path)
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });
            }

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

                final String result = response.body().string();//这句话必须放到子线程里


                System.out.println("OkHttUitls 线程名 : " + Thread.currentThread().getName());

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onSuccess(result);
                    }
                });

            }
        });
    }


    }





你可能感兴趣的:(OKHttp 网路拦截器 与 okhttp封装)