1. 程式人生 > >OKHttp 網路攔截器 與 okhttp封裝

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<String,String> 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<String, String> 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<String, String> 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);
                    }
                });

            }
        });
    }

    }