美文网首页
基于OkHttp3封装的一个单例

基于OkHttp3封装的一个单例

作者: GODANDDEVIL | 来源:发表于2020-03-14 12:14 被阅读0次
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpClientManager {

    private OkHttpClient myOkHttpClient;

    public static OkHttpClientManager getInstance(){
        return OkHttpClientManagerHolder.INSTANCE;
    }

    private static class OkHttpClientManagerHolder{
        private static final OkHttpClientManager INSTANCE = new OkHttpClientManager();
    }

    private OkHttpClientManager(){
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        clientBuilder.readTimeout(20, TimeUnit.SECONDS);//读取超时
        clientBuilder.connectTimeout(6, TimeUnit.SECONDS);//连接超时
        clientBuilder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
        //信任所有服务器地址
        clientBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                //设置为true
                return true;
            }
        });
        //支持HTTPS请求,跳过证书验证
        clientBuilder.sslSocketFactory(createSSLSocketFactory(),new TrustAllCerts());
        myOkHttpClient = clientBuilder.build();
    }
    /**
     * 生成安全套接字工厂,用于https请求的证书跳过
     * @return
     */
    public SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }
    /**
     * 用于信任所有证书
     */
    class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }



    /**
     * post请求上传键值对,构造RequestBody
     */
    private RequestBody setMapRequestBody(Map<String, String>bodyParams){
        RequestBody requestBody = null;
        FormBody.Builder builder = new FormBody.Builder();
        if (bodyParams!=null){
            //通过keySet()获取所有key
            for (String key : bodyParams.keySet()) {
                //遍历bodyParams,builder添加键值对
                builder.add(key, Objects.requireNonNull(bodyParams.get(key)));
            }
        }
        requestBody = builder.build();
        return requestBody;
    }
    /**
     * post请求上传字符串,构造RequestBody
     */
    private RequestBody setStringRequestBody(String value,String mediaTypeString){
        RequestBody requestBody = null;
        if (value!=null && mediaTypeString!=null){
            MediaType mediaType = MediaType.parse(mediaTypeString);
            //通过RequestBody.create创建RequestBody对象
            requestBody = RequestBody.create(mediaType,value);
        }
        return requestBody;
    }
    /**
     * post请求上传文件,传入文件路径和类型,构造RequestBody
     */
    private RequestBody setFileRequestBody(String filePath,String mediaTypeString){
        RequestBody requestBody = null;
        if (filePath!=null && mediaTypeString!=null){
            MediaType mediaType = MediaType.parse(mediaTypeString);
            File file = new File(Environment.getExternalStorageDirectory(),filePath);
            //通过RequestBody.create创建RequestBody对象
            requestBody = RequestBody.create(mediaType,file);
        }
        return requestBody;
    }
    /**
     * post请求上传Multipart数据,构造RequestBody
     */
    private RequestBody setMultipartRequestBody(Map<String, String>bodyParams, Map<String, String>fileParams, Map<String, String>mediaTypeParams){
        RequestBody requestBody = null;
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (bodyParams!=null){
            //通过keySet()获取所有key
            for (String key : bodyParams.keySet()) {
                //遍历bodyParams,builder添加键值对
                builder.addFormDataPart(key, Objects.requireNonNull(bodyParams.get(key)));
            }
        }
        if (fileParams!=null && mediaTypeParams!=null){
            //通过keySet()获取所有key
            for (String key : fileParams.keySet()) {
                //fileParams里key是filePath,value是name(这个name供服务器使用)
                //mediaTypeParams里的key与fileParams的相同,value是mediaType
                String name = fileParams.get(key);
                String mediaTypeString = mediaTypeParams.get(key);
                MediaType mediaType = MediaType.parse(Objects.requireNonNull(mediaTypeString));
                File file = new File(Environment.getExternalStorageDirectory(),key);
                RequestBody fileRequestBody = RequestBody.create(mediaType,file);
                String fileName = getFileName(key);
                //builder添加键值对
                builder.addFormDataPart(Objects.requireNonNull(name),fileName,fileRequestBody);
            }
        }
        requestBody = builder.setType(MultipartBody.FORM).build();
        return requestBody;
    }

    /**
     * 判断需要上传的数据类型(包含Multipart),返回RequestBody
     */
    private RequestBody judgeRequestBody(Map<String, String>bodyParams, Map<String, String>fileParams, Map<String, String>mediaTypeParams, String value, String filePath, String mediaTypeString){
        RequestBody requestBody = null;
        //键值对
        if (bodyParams!=null && fileParams==null && mediaTypeParams==null && value==null && filePath==null){
            requestBody = setMapRequestBody(bodyParams);
        }
        //字符串
        if (value!=null && mediaTypeString!=null && bodyParams==null && fileParams==null && mediaTypeParams==null && filePath==null){
            requestBody = setStringRequestBody(value,mediaTypeString);
        }
        //文件
        if (filePath!=null && mediaTypeString!=null && bodyParams==null && fileParams==null && mediaTypeParams==null && value==null){
            requestBody = setFileRequestBody(filePath,mediaTypeString);
        }
        //Multipart
        if (bodyParams!=null && fileParams!=null && mediaTypeParams!=null && value==null && filePath==null){
            requestBody = setMultipartRequestBody(bodyParams,fileParams,mediaTypeParams);
        }
        return requestBody;
    }
    /**
     *判断需要上传的数据类型(不包含Multipart),返回requestBody
     */
    private RequestBody whatRequestBody(Map<String, String>bodyParams, String value, String filePath, String mediaTypeString){
        RequestBody requestBody = null;
        //键值对
        if (bodyParams!=null && value==null && filePath==null){
            requestBody = setMapRequestBody(bodyParams);
        }
        //字符串
        if (value!=null && mediaTypeString!=null && bodyParams==null && filePath==null){
            requestBody = setStringRequestBody(value,mediaTypeString);
        }
        //文件
        if (filePath!=null && mediaTypeString!=null && bodyParams==null && value==null){
            requestBody = setFileRequestBody(filePath,mediaTypeString);
        }
        return requestBody;
    }

    /**
     *创建post请求的Call对象
     */
    private Call getPostCall(String url,RequestBody requestBody){
        Call call = null;
        if (url!=null && requestBody!=null){
            //1、创建request对象
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            //2、创建call对象
            call = myOkHttpClient.newCall(request);
        }
        return call;
    }
    /**
     *创建get请求的Call对象
     */
    private Call getGetCall(String url){
        Call call = null;
        if (url!=null){
            //1、创建request对象
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            //2、创建call对象
            call = myOkHttpClient.newCall(request);
        }
        return call;
    }

    /**
     *根据路径获取文件名
     */
    public String getFileName(String filePath){
        int start = filePath.lastIndexOf("/");
        int end = filePath.lastIndexOf(".");
        if (start!=-1 && end!=-1) {
            return filePath.substring(start+1, end);
        }
        else {
            return null;
        }
    }

    /**
     * 判断网络是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            //如果仅仅是用来判断网络连接
            //则可以使用cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (NetworkInfo networkInfo : info) {
                    if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }



    /**
     * 同步get请求,传入url参数
     */
    public Response getRequestSync(String url){
        //创建call对象
        Call call = getGetCall(url);
        //执行call得到response
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 同步post请求,上传键值对
     */
    public Response postMapRequestSync(String url, Map<String, String>bodyParams){
        //创建requestBody对象
        RequestBody requestBody = setMapRequestBody(bodyParams);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //执行call得到response
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 同步post请求,上传字符串
     */
    public Response postStringRequestSync(String url, String value, String mediaTypeString){
        //创建requestBody对象
        RequestBody requestBody = setStringRequestBody(value,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //执行call得到response
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 同步post请求,上传文件
     */
    public Response postFileRequestSync(String url, String filePath, String mediaTypeString){
        //创建requestBody对象
        RequestBody requestBody = setFileRequestBody(filePath,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //执行call得到response
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 同步post请求,直接传入requestBody
     */
    public Response postRequestBodyRequestSync(String url, RequestBody requestBody){
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //执行call得到response
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 同步post请求(不包含Multipart),直接传入参数,根据参数判断上传什么类型数据
     */
    public Response postRequestSync(String url, Map<String, String>bodyParams, String value, String filePath, String mediaTypeString){
        //创建requestBody对象
        RequestBody requestBody = whatRequestBody(bodyParams,value,filePath,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //执行call得到response
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 同步post请求(包含Multipart),直接传入参数,根据参数判断上传什么类型数据
     */
    public Response postRequestAllTypeSync(String url, Map<String, String>bodyParams, Map<String, String>fileParams, Map<String, String>mediaTypeParams, String value, String filePath, String mediaTypeString){
        //创建requestBody对象
        RequestBody requestBody = judgeRequestBody(bodyParams,fileParams,mediaTypeParams,value,filePath,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        Response response = null;
        try{
            response = call.execute();
        } catch (IOException e){
            e.printStackTrace();
        }
        return response;
    }





    /**
     * 自定义网络接口回调
     */
    public interface CustomCallBack{
        void success(Call call, Response response) throws IOException;
        void failed(Call call, IOException e);
    }
    /**
     * 异步get请求
     */
    public void getRequestASync(String url, final CustomCallBack customCallBack){
        //创建一个call对象
        Call call = getGetCall(url);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                customCallBack.success(call,response);

            }
        });
    }
    /**
     * 异步post请求,上传键值对
     */
    public void postMapRequestASync(String url, Map<String, String>bodyParams, final CustomCallBack customCallBack){
        //创建requestBody对象
        RequestBody requestBody = setMapRequestBody(bodyParams);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                customCallBack.success(call,response);
            }
        });
    }
    /**
     * 异步post请求,上传字符串
     */
    public void postStringRequestASync(String url, String value, String mediaTypeString, final CustomCallBack customCallBack){
        //创建requestBody对象
        RequestBody requestBody = setStringRequestBody(value,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                customCallBack.success(call,response);
            }
        });
    }
    /**
     * 异步post请求,上传文件
     */
    public void postFileRequestASync(String url, String filePath, String mediaTypeString, final CustomCallBack customCallBack){
        //创建requestBody对象
        RequestBody requestBody = setFileRequestBody(filePath,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                customCallBack.success(call,response);
            }
        });
    }
    /**
     * 异步post请求,直接传入requestBody
     */
    public void postRequestBodyRequestASync(String url, RequestBody requestBody, final CustomCallBack customCallBack){
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                customCallBack.success(call,response);
            }
        });
    }
    /**
     * 异步post请求(不包含Multipart),直接传入参数,根据参数判断上传什么类型数据
     */
    public void postRequestASync(String url, Map<String, String>bodyParams, String value, String filePath, String mediaTypeString, final CustomCallBack customCallBack){
        //创建requestBody对象
        RequestBody requestBody = whatRequestBody(bodyParams,value,filePath,mediaTypeString);
        //创建call对象
        Call call = getPostCall(url,requestBody);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                customCallBack.success(call,response);
            }
        });
    }
    /**
     * 异步post请求(包含Multipart),直接传入参数,根据参数判断上传什么类型数据
     */
    public void postRequestAllTypeASync(String url, Map<String, String>bodyParams, Map<String, String>fileParams, Map<String, String>mediaTypeParams, String value, String filePath, String mediaTypeString, final CustomCallBack customCallBack){
        //创建requestBody对象
        RequestBody requestBody = judgeRequestBody(bodyParams,fileParams,mediaTypeParams,value,filePath,mediaTypeString);
        //创建Call对象
        Call call = getPostCall(url,requestBody);
        //将请求加入调度,重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                customCallBack.failed(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                customCallBack.success(call,response);
            }
        });
    }



}

用例:

OkHttpClientManager m = OkHttpClientManager.getInstance();
                String url = "https://www.taobao.com";
                m.getRequestASync(url, new OkHttpClientManager.CustomCallBack() {
                    @Override
                    public void success(Call call, Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.v("==========",response.body().string());
                                } catch (IOException e) {
                                    Log.v("==========","failed");
                                    e.printStackTrace();
                                }
                                getButton.setText("success");
                            }
                        });

                    }

                    @Override
                    public void failed(Call call, IOException e) {

                    }
                });

相关文章

网友评论

      本文标题:基于OkHttp3封装的一个单例

      本文链接:https://www.haomeiwen.com/subject/jdjvshtx.html