Android 对OkHttp的封装

作者: cnbzlj 发布时间: 2019-09-19 浏览: 1786 次 编辑

不废话,需求:根据服务器API封装网络请求,怎么办?

简单封装okhttp的get,post,put,delete请求:

PersistentCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));
        HttpUtils.okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .build();

/**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     *
     * @param url
     * @param params
     * @return
     */
    public static String attachHttpGetParams(String url, LinkedHashMap<String, String> params) {
 
        Iterator<String> keys = params.keySet().iterator();
        Iterator<String> values = params.values().iterator();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("?");
 
        for (int i = 0; i < params.size(); i++) {
            String value = null;
            try {
                value = URLEncoder.encode(values.next(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
 
            stringBuffer.append(keys.next() + "=" + value);
            if (i != params.size() - 1) {
                stringBuffer.append("&");
            }
        }
 
        return url + stringBuffer.toString();
    }
 
    public static void HTTP_GET_IMPROVE(final String url, final HTTPInterface httpInterface, final int count) {
 
        Request request = builder.url(url).method("GET", null).build();
        //3.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //4.请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpInterface.onFailure(call, e);
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
//                Log.e("HTTP_GET_IMPROVE", " code=" + code + " url=" + url + " count=" + count);
 
                int myCount = count - 1;
                if (code != 200 && count > 0) {
                    HTTP_GET_IMPROVE(url, httpInterface, myCount);
                } else {
 
                    httpInterface.onResponse(call, response);
                }
 
            }
        });
 
    }
 
    public static void HTTP_POST_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {
 
        //1.创建OkHttpClient对象
//        OkHttpClient okHttpClient = new OkHttpClient();
        //2.通过new FormBody()调用build方法,创建一个RequestBody,可以用add添加键值对
        //3.创建Request对象,设置URL地址,将RequestBody作为post方法的参数传入
//        Request request = new Request.Builder().url(url).post(requestBody).build();
 
        final Request request = builder.url(url).post(requestBody).build();
        //4.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //5.请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpInterface.onFailure(call, e);
 
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                int myCount = count - 1;
                if (code != 200 && count > 0) {
                    HTTP_GET_IMPROVE(url, httpInterface, myCount);
                } else {
 
//                    Log.e("TAG", "POST JSESSIONID= " + response.header("JSESSIONID"));
                    httpInterface.onResponse(call, response);
                }
 
            }
        });
 
 
    }
 
    public static void HTTP_PATCH_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {
 
        //1.创建OkHttpClient对象
//        OkHttpClient okHttpClient = new OkHttpClient();
        //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
        Request request = new Request.Builder().url(url).method("PATCH", requestBody).build();
        //3.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //4.请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpInterface.onFailure(call, e);
 
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                int myCount = count - 1;
                if (code != 200 && count > 0) {
                    HTTP_GET_IMPROVE(url, httpInterface, myCount);
                } else {
                    httpInterface.onResponse(call, response);
                }
 
            }
        });
 
    }
 
    public static void HTTP_PUT_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {
 
        //1.创建OkHttpClient对象
//        OkHttpClient okHttpClient = new OkHttpClient();
        //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
        Request request = new Request.Builder().url(url).method("PUT", requestBody).build();
        //3.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //4.请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpInterface.onFailure(call, e);
 
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                int myCount = count - 1;
                if (code != 200 && count > 0) {
                    HTTP_GET_IMPROVE(url, httpInterface, myCount);
                } else {
                    httpInterface.onResponse(call, response);
                }
 
            }
        });
 
    }
 
    public static void HTTP_DELETE_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {
 
        //1.创建OkHttpClient对象
//        OkHttpClient okHttpClient = new OkHttpClient();
        //2.通过new FormBody()调用build方法,创建一个RequestBody,可以用add添加键值对
        //3.创建Request对象,设置URL地址,将RequestBody作为post方法的参数传入
        Request request = new Request.Builder().url(url).delete(requestBody).build();
        //4.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //5.请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpInterface.onFailure(call, e);
 
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                int myCount = count - 1;
                if (code != 200 && count > 0) {
                    HTTP_GET_IMPROVE(url, httpInterface, myCount);
                } else {
                    httpInterface.onResponse(call, response);
                }
 
            }
        });
    }
 
    /**
     */
    public static void HTTPUploadImage(final String url, final String imagePath, final HTTPInterface httpInterface, final int count) {
 
        Log.e("imagePath", "HTTPUploadImage " + imagePath);
        File file = new File(imagePath);
        RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("files", imagePath, image)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
 
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
 
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                int myCount = count - 1;
                if (code != 200 && count > 0) {
                    HTTPUploadImage(url, imagePath, httpInterface, myCount);
                } else {
                    httpInterface.onResponse(call, response);
                }
 
            }
        });
 
    }

根据服务器的API封装:

public static void outProduct(String token, String product_id, HttpUtils.HTTPInterface httpInterface) {
 
        RequestBody requestBody = new FormBody.Builder()
                .add("token", token)
                .add("product_id", product_id)
                .build();
        String url = HttpUtils.OUT_PRODUCT;
        HttpUtils.HTTP_POST_IMPROVE(url, requestBody, httpInterface, HttpUtils.HTTP_TOTAL_COUNT);
 
    }


这样的好处是网络请求的API与具体的界面分离了,我之前写代码,每次写完界面,再做界面的请求,导致很多界面有同样的网络请求,不停复制,修改代码,浪费时间。封装代码也是一个程序员技术提升的体现。