Android Okhttp工具类的封装(okhttpUtils)

Android Okhttp工具类

Android Okhttp工具类的封装(okhttpUtils)

近期的项目频繁使用到了网络交互,采用的是第三方类库okhttp
以下是我对okhttp主要使用到的方法进行的封装。
github源码地址:https://github.com/square/okhttp

主要是分为以下三种使用模式(post请求)

  1. post请求(参数+cookie)
  2. post请求(单文件+参数+cookie)
  3. post请求(多文件+参数+cookie)

下面是代码

代码中的变量声明

  private static volatile OkhttpUtil instance;
  private static final String TAG = "OkhttpUtil";
  public static Handler handler = new Handler();
  private final HashMap> cookieStore = new HashMap<>();

双重检测锁-单例模式

 /**
     * 双重检测锁-单例模式
     *
     * @return
     */
    public static OkhttpUtil getInstance() {
        if (instance == null) {
            synchronized (OkhttpUtil.class) {
                if (instance == null) {
                    instance = new OkhttpUtil();
                }
            }
        }
        return instance;
    }

然后是post请求(参数+cookie)

 /**
     * @网络请求--post请求(参数+cookie)
     * url地址,map是参数集合,name是header的key,value是header的value,CallBack回调方法
     */
    public void postParameter(String url, Map map, String name, String value, final CallBack callback) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl httpUrl, List list) {//存储用户身份凭证
                cookieStore.put(httpUrl.host(), list);
            }

            @Override
            public List loadForRequest(HttpUrl httpUrl) {
                List cookies = cookieStore.get(httpUrl.host());
                return cookies != null ? cookies : new ArrayList();
            }
        }).build();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry entry : map.entrySet()) {//遍历map集合进行添加
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
        MultipartBody requestBody = builder.build();
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .header(name, value)//将身份凭证作为头参数,访问时携带发送
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e(TAG, "onFailure:" + e.getCause().getStackTrace() + e.getMessage());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailed( e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String result = response.body().string();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess( result);
                        }
                    });
                }
            }
        });
    }

下面是post请求(参数+cookie)使用时的代码

 private void post() {
        OkhttpUtil okhttpUtil = new OkhttpUtil();
        String url = "这里是所要访问的url地址;
        Map map = new HashMap<>();//参数map集合
        map.put("account", account);//向map集合中添加参数
        map.put("pw", pw);
        okhttpUtil.postParameter(url, map, new CallBack() {
            @Override
            public void onSuccess(String request) {//回调访问成功
                final Gson gson = new Gson();
                loginBean newsBean = gson.fromJson(request, loginBean.class);//解析传回的json数据
                String message = newsBean.getMessage();  //获取传回的message
            }

            @Override
            public void onFailed(Exception e) {//回调访问失败
                Toast.makeText(LoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

好了,以上就是post请求(参数+cookie)的使用过程
那么下面就是 post请求(单文件+参数+cookie)了

 /**
     * @网络请求--post请求(单文件+参数+cookie)
     * url地址,map是参数集合,f是文件,name是header的key,value是header的value,CallBack回调方法
     */
    public void postFileCookie(String url, String f, Map map, String name, String value, final CallBack callback) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl httpUrl, List list) {
                cookieStore.put(httpUrl.host(), list);
            }

            @Override
            public List loadForRequest(HttpUrl httpUrl) {
                List cookies = cookieStore.get(httpUrl.host());
                return cookies != null ? cookies : new ArrayList();
            }
        }).build();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry entry : map.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
        File file = new File(f);
        if (file != null) {
            builder.addFormDataPart("file", file.getName(),
                    RequestBody.create(MediaType.parse("file/*"), file));
        }
        MultipartBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .header(name, value)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e(TAG, "onFailure:" + e.getCause().getStackTrace() + e.getMessage());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailed( e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(result);
                    }
                });
            }
        });
    }

下面是post请求(单文件+参数+cookie)使用时的代码

 private void post() {
        OkhttpUtil okhttpUtil = new OkhttpUtil();
        String url = "这里是所要访问的url地址";
        Map map = new HashMap<>();
        map.put("enterprise", "enterprise");//向map集合中添加参数
        map.put("checklogid", checklogid);
        okhttpUtil.postFileCookie(url, savedFile, map, "cookie", "JSESSIONID=" + getToken(), new CallBack() {
            @Override
            public void onSuccess(String request) {//请求成功
                final Gson gson = new Gson();
                updateBean newsBean = gson.fromJson(request, updateBean.class);//解析传回的json数据
                String message = newsBean.getMessage();//获取想要拿到的数据
            }
            @Override
            public void onFailed(Exception e) {//请求失败
                Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

以下是post请求(多文件+参数+cookie)

 /**
     * @网络请求--post请求(多文件+参数+cookie)
     *  url地址,map是参数集合,list是文件集合,name是header的key,value是header的value,CallBack回调方法
     */
    public void postFileParameterCookie(String url, Map map, List list, String name, String value, final CallBack callback) {
        if (list.size() > 0) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl httpUrl, List list) {
                    cookieStore.put(httpUrl.host(), list);
                }

                @Override
                public List loadForRequest(HttpUrl httpUrl) {
                    List cookies = cookieStore.get(httpUrl.host());
                    return cookies != null ? cookies : new ArrayList();
                }
            }).build();
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (int i = 0; i < list.size(); i++) {遍历集合中的文件
                File file = new File(list.get(i));
                if (file != null) {
                    builder.addFormDataPart("file", file.getName(),
                            RequestBody.create(MediaType.parse("file/*"), file));
                }
            }
            for (Map.Entry entry : map.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
            MultipartBody requestBody = builder.build();
            Request request = new Request.Builder()
                    .url(url)
                    .header(name, value)//身份标识
                    .post(requestBody)
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {//访问失败
                    Log.e(TAG, "onFailure:" + e.getCause().getStackTrace() + e.getMessage());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailed(e);
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {//访问成功
                    final String result = response.body().string();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess(result);
                        }
                    });
                }
            });
        }
    }

下面是post请求(多文件+参数+cookie)使用时的代码

 private void post(List list) {
        String url = "访问的url地址";
        OkhttpUtil okhttpUtil = new OkhttpUtil();
        Map map= new HashMap<>();
        map.put("rectifyday", rectifyday);		//向map中添加参数
        map.put("treatmethod", treatmethod);
        okhttpUtil.postFileParameterCookie(url, map, list, "cookie", "JSESSIONID=" + getToken(), new CallBack() {
            @Override
            public void onSuccess(String request) {
                final Gson gson = new Gson();
                updateBean newsBean = gson.fromJson(request, updateBean.class);//解析传回的json数据
                String message = newsBean.getMessage();//获取想要拿到的数据
            }
            @Override
            public void onFailed( Exception e) {
                Toast.makeText(UpdateActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

其中的CallBack是另写的一个接口,代码如下:

public interface CallBack{
    void onSuccess(String request);
    void onFailed(Exception e);
}

以上就是我对okhttp的封装。

你可能感兴趣的:(Android)