安卓封装OkHttp

简单封装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与具体的界面分离了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值