精华内容
下载资源
问答
  • okhttp3封装
    千次阅读
    2022-01-28 19:12:58

    先贴工具类的代码

    object HttpUtil {
        //这是Get请求
        fun sendOkHttpGetRequest(address:String, callback: okhttp3.Callback){
            val client= OkHttpClient()
            val request= Request.Builder().url(address).build()
         //必须调用enqueue方法,异步网络请求
            client.newCall(request).enqueue(callback)
        }
        //这是Post请求
        fun sendOkHttpPostRequest(address: String, requestBody: RequestBody, callback:okhttp3.Callback){
            val client=OkHttpClient()
            val request=Request.Builder().url(address).post(requestBody).build()
        //必须调用enqueue方法,异步网络请求
            client.newCall(request).enqueue(callback)
        }
    }

    需要使用工具类的时候就HttpUtil.fun()

     HttpUtil.sendOkHttpGetRequest("https://wanandroid.com/user_article/list/$curPage/json",
                object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
    
                    }
    
                    override fun onResponse(call: Call, response: Response) {
                        //网络请求成功后,解析json数据
                        val responseData = response.body?.string()
                        //调用方法刷新recycleView数据,但注意在此函数内是子线程不能直接更新ui
                        recycleViewData(responseData)
                    }
                })
     val username = mEdUsername.text.toString()
            val password = mEdPassword.text.toString()
            //Post请求需要先bulid requestBody
            val requestBody = FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build()
            HttpUtil.sendOkHttpPostRequest(
                "https://www.wanandroid.com/user/login",
                requestBody,
                object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
    
                    }
    
                    override fun onResponse(call: Call, response: Response) {
                        //网络请求成功后,解析json数据
                        val responseData = response.body?.string()
                    }
                })

    更多相关内容
  • OkHttp3 网络框架的封装! 异步,同步
  • okHttp3封装

    2020-12-10 11:54:11
    public class OkHttp3Util { /** * 懒汉 安全 加同步 * 私有的静态成员变量 只声明不创建 * 私有的构造方法 * 提供返回实例的静态方法 */ private static OkHttpClient okHttpClient = null; private ...
    public class OkHttp3Util {
        /**
         * 懒汉 安全 加同步
         * 私有的静态成员变量 只声明不创建
         * 私有的构造方法
         * 提供返回实例的静态方法
         */
        private static OkHttpClient okHttpClient = null;
    
        private OkHttp3Util() {
        }
    
        public static OkHttpClient getInstance() {
            if (okHttpClient == null) {
                //加同步安全
                synchronized (OkHttp3Util.class) {
                    if (okHttpClient == null) {
                        //okhttp可以缓存数据....指定缓存路径
                        File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
                        //指定缓存大小
                        int cacheSize = 10 * 1024 * 1024;
                        okHttpClient = new OkHttpClient.Builder()//构建器
                                .connectTimeout(15 * 1000, TimeUnit.MILLISECONDS)//连接超时
                                .writeTimeout(15 * 1000, TimeUnit.MILLISECONDS)//写入超时
                                .readTimeout(15 * 1000, TimeUnit.MILLISECONDS)//读取超时
                                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))//设置缓存
                                .build();
                    }
                }
            }
            return okHttpClient;
        }
    
        /**
         * get请求
         * 参数1 url
         * 参数2 回调Callback
         */
        public static void doGet(String url, Callback callback) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            //创建Request
            Request request = new Request.Builder().url(url).build();
            //得到Call对象
            Call call = okHttpClient.newCall(request);
            //执行异步请求
            call.enqueue(callback);
        }
    
        public static void doGet(String url, Map<String, String> params, Callback callback) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            //创建Request
            Request.Builder reqBuild = new Request.Builder();
            HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                    .newBuilder();
            if (params != null && params.size() > 0) {
                Set<String> strings = params.keySet();
                for (String key : strings) {
                    urlBuilder.addQueryParameter(key, params.get(key));
                }
            }
            reqBuild.url(urlBuilder.build());
            Request request = reqBuild.build();
            //得到Call对象
            Call call = okHttpClient.newCall(request);
            //执行异步请求
            call.enqueue(callback);
        }
    
        /**
         * post请求
         * 参数1 url
         * 参数2 Map<String, String> params post请求的时候给服务器传的数据
         * add..("","")
         * add()
         */
        public static void doPost(String url, Map<String, String> params, Callback callback) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            //3.x版本post请求换成FormBody 封装键值对参数
            FormBody.Builder builder = new FormBody.Builder();
            //遍历集合
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
            Log.d("doPost", "==========builder==========" + builder);
            //创建Request
            Request request = new Request.Builder().url(url)
                    .post(builder.build()).build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(callback);
        }
    
        public static String doPostSync(String url, Map<String, String> params) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            //3.x版本post请求换成FormBody 封装键值对参数
            FormBody.Builder builder = new FormBody.Builder();
            //遍历集合
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
            Log.d("doPost", "==========builder==========" + builder);
            //创建Request
            Request request = new Request.Builder().url(url)
                    .post(builder.build()).build();
            Call call = okHttpClient.newCall(request);
            Response response = null;
            try {
                response = call.execute();
                return response.isSuccessful() ? response.body().string() : null;
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("doPostSync", "the response code > " + response.code());
            return null;
        }
    
        /**
         * post请求上传文件....包括图片....流的形式传任意文件...
         * 参数1 url
         * file表示上传的文件
         * fileName....文件的名字,,例如aaa.jpg
         * params ....传递除了file文件 其他的参数放到map集合
         */
        public static void uploadFile(String url, File file, String fileName, Map<String, String> params) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            //参数
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addFormDataPart(key, params.get(key));
                }
            }
            //文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,此处应该改变
            builder.addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), file));
            //构建
            MultipartBody multipartBody = builder.build();
            //创建Request
            Request request = new Request.Builder().url(url).post(multipartBody).build();
            //得到Call
            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 {
                    //上传成功回调 目前不需要处理
                    if (response.isSuccessful()) {
                        String s = response.body().string();
                    }
                }
            });
        }
    
    
        /**
         * 上传多张图片及参数
         *
         * @param url     URL地址
         * @param params  参数
         * @param pic_key 上传图片的关键字
         * @param files   图片路径
         */
        public static void sendMultipart(String url, Map<String, String> params, String pic_key, List<File> files) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            //参数
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addFormDataPart(key, params.get(key));
                }
            }
            if (files != null) {
                for (File file : files) {
                    builder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));
                }
            }
            //构建
            MultipartBody multipartBody = builder.build();
            //创建Request
            Request request = new Request.Builder().url(url).post(multipartBody).build();
            //得到Call
            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 {
                    //上传成功回调 目前不需要处理
                    if (response.isSuccessful()) {
                        String s = response.body().string();
                        System.out.println("上传---------------" + s);
                    }
                }
            });
        }
    
        /**
         * 上传多张图片及参数
         *
         * @param url     URL地址
         * @param params  参数
         * @param pic_key 上传图片的关键字
         * @param files   图片路径
         */
        public static void sendMultipart2(String url, Map<String, String> params, String pic_key, List<File> files, Callback callback) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            //参数
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addFormDataPart(key, params.get(key));
                }
            }
            if (files != null) {
                for (File file : files) {
                    builder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));
                }
            }
            //构建
            MultipartBody multipartBody = builder.build();
            //创建Request
            Request request = new Request.Builder().url(url).post(multipartBody).build();
            //得到Call
            Call call = okHttpClient.newCall(request);
            //执行请求
            call.enqueue(callback);
        }
    
        /**
         * 上传多张图片及参数
         *
         * @param url     URL地址
         * @param params  参数
         * @param pic_key 上传图片的关键字
         * @param files   图片路径
         */
        public static void sendSolaMultipart(String url, Map<String, String> params, String pic_key, File files, Callback callback) {
            //创建OkHttpClient请求对象
            OkHttpClient okHttpClient = getInstance();
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            //参数
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addFormDataPart(key, params.get(key));
                }
            }
            if (files != null) {
                builder.addFormDataPart(pic_key, files.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), files));
            }
            //构建
            MultipartBody multipartBody = builder.build();
            //创建Request
            Request request = new Request.Builder().url(url).post(multipartBody).build();
            //得到Call
            Call call = okHttpClient.newCall(request);
            //执行请求
            call.enqueue(callback);
        }
    
        /**
         * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
         * 参数一:请求Url
         * 参数二:请求的JSON
         * 参数三:请求回调
         */
        public static void doPostJson(String url, String jsonParams, Callback callback) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
            Request request = new Request.Builder().url(url).post(requestBody)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();
            Call call = getInstance().newCall(request);
            call.enqueue(callback);
        }
    
        public static void doPostJsonLocal(String url, String jsonParams, Callback callback) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
            Request request = new Request.Builder().url(url).post(requestBody)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();
            Call call = getInstance().newBuilder()
                    .connectTimeout(5 * 1000, TimeUnit.MILLISECONDS)//连接超时
                    .writeTimeout(15 * 1000, TimeUnit.MILLISECONDS)//写入超时
                    .readTimeout(15 * 1000, TimeUnit.MILLISECONDS)//读取超时
                    .build()
                    .newCall(request);
            call.enqueue(callback);
        }
    
        /**
         * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
         * 参数er:请求Url
         * 参数san:保存文件的文件夹....download
         */
        public static void download(final Activity context, final String url, final String saveDir) {
            Request request = new Request.Builder().url(url).build();
            Call call = getInstance().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
    
                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    try {
                        is = response.body().byteStream();//以字节流的形式拿回响应实体内容
                        //apk保存路径
                        final String fileDir = isExistDir(saveDir);
                        //文件
                        File file = new File(fileDir, getNameFromUrl(url));
                        fos = new FileOutputStream(file);
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                        fos.flush();
    //                    context.runOnUiThread(new Runnable() {
    //                        @Override
    //                        public void run() {
    //                            Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
    //                        }
    //                    });
    //                    //apk下载完成后 调用系统的安装方法
    //                    Intent intent = new Intent(Intent.ACTION_VIEW);
    //                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    //                    context.startActivity(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (is != null) is.close();
                        if (fos != null) fos.close();
                    }
                }
            });
        }
    
        /**
         * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
         * 参数er:请求Url
         * 参数san:保存文件的文件夹....download
         */
        public static void download2(final String url, Callback callback) {
            Request request = new Request.Builder().url(url).build();
            Call call = getInstance().newCall(request);
            call.enqueue(callback);
        }
    
        /**
         * 判断下载目录是否存在......并返回绝对路径
         *
         * @param saveDir
         * @return
         * @throws IOException
         */
        public static String isExistDir(String saveDir) throws IOException {
            // 下载位置
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
                if (!downloadFile.mkdirs()) {
                    downloadFile.createNewFile();
                }
                String savePath = downloadFile.getAbsolutePath();
                Log.e("savePath", savePath);
                return savePath;
            }
            return null;
        }
    
        /**
         * @param url
         * @return 从下载连接中解析出文件名
         */
        private static String getNameFromUrl(String url) {
            return url.substring(url.lastIndexOf("/") + 1);
        }
    }
    展开全文
  • 今天在这里分享慕课一位老师基于OkHttp封装的一个思路,希望对大家有帮助。 首先,我们看一下Okhttp的基本使用 发送异步GET请求 1、new OkHttpClient; 2、构造Request对象; 3、通过前两步中的对象构建Call对象; 4...

    OkHttp3封装网络请求框架

    网络请求是开发中最基础的功能,框架原生API不便于复用。今天在这里分享慕课一位老师基于OkHttp封装的一个思路,希望对大家有帮助。

    首先,我们看一下Okhttp的基本使用

    发送异步GET请求
    1、new OkHttpClient;
    2、构造Request对象;
    3、通过前两步中的对象构建Call对象;
    4、通过Call.enqueue(Callback)方法来提交异步请求;

    String url = "http://wwww.baidu.com";
    OkHttpClient okHttpClient = new OkHttpClient();
    final Request request = new Request.Builder()
            .url(url)
            .get()//默认就是GET请求,可以不写
            .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d(TAG, "onFailure: ");
        }
    
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d(TAG, "onResponse: " + response.body().string());
        }
    });
    

    一个简单的get请求需要使用这么多代码,还有post请求?文件上传下载等等?

    所以在实际开发中,完全不会这么用,原因如下:
    1、代码冗余,几乎不可复用
    2、一旦底层API改动,所有上层的网络请求代码度需要改动
    3、没有进行封装

    所以我们必须对OKhttp进行封装,如何封装那?

    封装思路

    img

    主要分为3部分的封装:
    1、Request的封装

    请求参数
    url
    请求对象
    2、OKhttp核心封装

    发送请求
    配置相关参数
    HTTPS的支持
    3、Callback的封装

    处理回调函数
    异常处理
    转发消息到我们的UI线程
    讲json转化为实体对象

    Request的封装

    封装所有的请求参数到hashmap中

    import java.io.FileNotFoundException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    /**
     * @author vision
     * 封装所有的请求参数到hashmap中
     */
    public class RequestParams {
    
        public ConcurrentHashMap<String, String> urlParams = new ConcurrentHashMap<String, String>();
        public ConcurrentHashMap<String, Object> fileParams = new ConcurrentHashMap<String, Object>();
    
        /**
         * Constructs a new empty {@code RequestParams} instance.
         */
        public RequestParams() {
            this((Map<String, String>) null);
        }
    
        /**
         * Constructs a new RequestParams instance containing the key/value string
         * params from the specified map.
         *
         * @param source the source key/value string map to add.
         */
        public RequestParams(Map<String, String> source) {
            if (source != null) {
                for (Map.Entry<String, String> entry : source.entrySet()) {
                    put(entry.getKey(), entry.getValue());
                }
            }
        }
    
        /**
         * Constructs a new RequestParams instance and populate it with a single
         * initial key/value string param.
         *
         * @param key   the key name for the intial param.
         * @param value the value string for the initial param.
         */
        public RequestParams(final String key, final String value) {
            this(new HashMap<String, String>() {
                {
                    put(key, value);
                }
            });
        }
    
        /**
         * Adds a key/value string pair to the request.
         *
         * @param key   the key name for the new param.
         * @param value the value string for the new param.
         */
        public void put(String key, String value) {
            if (key != null && value != null) {
                urlParams.put(key, value);
            }
        }
    
        public void put(String key, Object object) throws FileNotFoundException {
    
            if (key != null) {
                fileParams.put(key, object);
            }
        }
    
        public boolean hasParams() {
            if(urlParams.size() > 0 || fileParams.size() > 0){
    
                return true;
            }
            return false;
        }
    
    
    

    生成request对象

    import java.io.File;
    import java.util.Map;
    
    import okhttp3.FormBody;
    import okhttp3.Headers;
    import okhttp3.MediaType;
    import okhttp3.MultipartBody;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    
    /**
     * @author vision
     * @function build the request
     * 生成request对象
     */
    public class CommonRequest {
        /**
         * create the key-value Request
         *
         * @param url
         * @param params
         * @return
         */
        public static Request createPostRequest(String url, RequestParams params) {
            return createPostRequest(url, params, null);
        }
    
        /**可以带请求头的Post请求
         * @param url
         * @param params
         * @param headers
         * @return
         */
        public static Request createPostRequest(String url, RequestParams params, RequestParams headers) {
            //添加请求体
            FormBody.Builder mFormBodyBuild = new FormBody.Builder();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.urlParams.entrySet()) {
                    mFormBodyBuild.add(entry.getKey(), entry.getValue());
                }
            }
            //添加请求头
            Headers.Builder mHeaderBuild = new Headers.Builder();
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.urlParams.entrySet()) {
                    mHeaderBuild.add(entry.getKey(), entry.getValue());
                }
            }
            FormBody mFormBody = mFormBodyBuild.build();
            Headers mHeader = mHeaderBuild.build();
    
    
            Request request = new Request.Builder().url(url).
                    post(mFormBody).
                    headers(mHeader)
                    .build();
            return request;
        }
    
        /**
         * ressemble the params to the url
         *
         * @param url
         * @param params
         * @return
         */
        public static Request createGetRequest(String url, RequestParams params) {
    
            return createGetRequest(url, params, null);
        }
    
        /**
         * 可以带请求头的Get请求
         * @param url
         * @param params
         * @param headers
         * @return
         */
        public static Request createGetRequest(String url, RequestParams params, RequestParams headers) {
            StringBuilder urlBuilder = new StringBuilder(url).append("?");
            if (params != null) {
                for (Map.Entry<String, String> entry : params.urlParams.entrySet()) {
                    urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            //添加请求头
            Headers.Builder mHeaderBuild = new Headers.Builder();
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.urlParams.entrySet()) {
                    mHeaderBuild.add(entry.getKey(), entry.getValue());
                }
            }
            Headers mHeader = mHeaderBuild.build();
            return new Request.Builder().
                    url(urlBuilder.substring(0, urlBuilder.length() - 1))
                    .get()
                    .headers(mHeader)
                    .build();
        }
    
        /**
         * @param url
         * @param params
         * @return
         */
        public static Request createMonitorRequest(String url, RequestParams params) {
            StringBuilder urlBuilder = new StringBuilder(url).append("&");
            if (params != null && params.hasParams()) {
                for (Map.Entry<String, String> entry : params.urlParams.entrySet()) {
                    urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            return new Request.Builder().url(urlBuilder.substring(0, urlBuilder.length() - 1)).get().build();
        }
    
        /**
         * 文件上传请求
         *
         * @return
         */
        private static final MediaType FILE_TYPE = MediaType.parse("application/octet-stream");
    
        public static Request createMultiPostRequest(String url, RequestParams params) {
    
            MultipartBody.Builder requestBody = new MultipartBody.Builder();
            requestBody.setType(MultipartBody.FORM);
            if (params != null) {
    
                for (Map.Entry<String, Object> entry : params.fileParams.entrySet()) {
                    if (entry.getValue() instanceof File) {
                        requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
                                RequestBody.create(FILE_TYPE, (File) entry.getValue()));
                    } else if (entry.getValue() instanceof String) {
    
                        requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
                                RequestBody.create(null, (String) entry.getValue()));
                    }
                }
            }
            return new Request.Builder().url(url).post(requestBody.build()).build();
        }
    }
    
    

    OKhttp核心封装

    import com.youdu.okhttp.cookie.SimpleCookieJar;
    import com.youdu.okhttp.https.HttpsUtils;
    import com.youdu.okhttp.listener.DisposeDataHandle;
    import com.youdu.okhttp.response.CommonFileCallback;
    import com.youdu.okhttp.response.CommonJsonCallback;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.concurrent.TimeUnit;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLSession;
    
    import okhttp3.Call;
    import okhttp3.Interceptor;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    /**
     * @author qndroid
     * @function 用来发送get, post请求的工具类,包括设置一些请求的共用参数,https支持
     */
    public class CommonOkHttpClient {
    
    
        private static final int TIME_OUT = 30;
    
        private static OkHttpClient mOkHttpClient;
    
    
        //client 配置
        static {
            OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    
    
            /**
             *  为所有请求添加请求头,看个人需求
             */
            okHttpClientBuilder.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("User-Agent", "Imooc-Mobile") // 标明发送本次请求的客户端
                            .build();
                    return chain.proceed(request);
                }
            });
                 okHttpClientBuilder.cookieJar(new SimpleCookieJar());
    
            //设置超时时间
            okHttpClientBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
            okHttpClientBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
            okHttpClientBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
            //支持重定向
            okHttpClientBuilder.followRedirects(true);
    
    
    
            //https支持
            okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
    
    
            /**
             * trust all the https point
             */
            okHttpClientBuilder.sslSocketFactory(HttpsUtils.initSSLSocketFactory(), HttpsUtils.initTrustManager());
            mOkHttpClient = okHttpClientBuilder.build();
        }
    
        public static OkHttpClient getOkHttpClient() {
            return mOkHttpClient;
        }
    
    
        /**
         * 通过构造好的Request,Callback去发送请求
         *
         * @param request
         * @param callback
         */
        public static Call get(Request request, DisposeDataHandle handle) {
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new CommonJsonCallback(handle));//CommonJsonCallback Callback回调
            return call;
        }
    
        public static Call post(Request request, DisposeDataHandle handle) {
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new CommonJsonCallback(handle));
            return call;
        }
    
        public static Call downloadFile(Request request, DisposeDataHandle handle) {
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new CommonFileCallback(handle));
            return call;
        }
    
    
    

    Callback的封装

    img

    定义OkHttpException

    public class OkHttpException extends Exception {
    		private static final long serialVersionUID = 1L;
    
    	/**
    	 * the server return code
    	 */
    	private int ecode;
    
    	/**
    	 * the server return error message
    	 */
    	private Object emsg;
    
    	public OkHttpException(int ecode, Object emsg) {
    		this.ecode = ecode;
    		this.emsg = emsg;
    	}
    
    	public int getEcode() {
    		return ecode;
    	}
    
    	public Object getEmsg() {
    		return emsg;
    	}
    }
    
    

    DisposeDataListener 回调事件处理

    public interface DisposeDataListener {
    
    	/**
    	 * 请求成功回调事件处理
    	 */
    	public void onSuccess(Object responseObj);
    
    	/**
    	 * 请求失败回调事件处理
    	 */
    	public void onFailure(Object reasonObj);
    
    }
    
    

    DisposeDataListener 在一层封装 DisposeDataHandle

    public class DisposeDataHandle
    {
    	public DisposeDataListener mListener = null;
    	public Class<?> mClass = null;//json->object  object.class  后面要解析的json实体类
    	public String mSource = null;
    
    	public DisposeDataHandle(DisposeDataListener listener)
    	{
    		this.mListener = listener;
    	}
    
    	public DisposeDataHandle(DisposeDataListener listener, Class<?> clazz)
    	{
    		this.mListener = listener;
    		this.mClass = clazz;
    	}
    
    	public DisposeDataHandle(DisposeDataListener listener, String source)
    	{
    		this.mListener = listener;
    		this.mSource = source;
    	}
    }
    
    

    CommonJsonCallback的封装

    import android.os.Handler;
    import android.os.Looper;
    
    import com.youdu.okhttp.exception.OkHttpException;
    import com.youdu.okhttp.listener.DisposeDataHandle;
    import com.youdu.okhttp.listener.DisposeDataListener;
    import com.youdu.okhttp.listener.DisposeHandleCookieListener;
    import com.youdu.adutil.ResponseEntityToModule;
    
    import org.json.JSONObject;
    
    import java.io.IOException;
    import java.util.ArrayList;
    
    import okhttp3.Call;
    import okhttp3.Callback;
    import okhttp3.Headers;
    import okhttp3.Response;
    
    /**
     * @author vision
     * @function
     *
     * 1、异常
     * 2、数据解析
     * 3、数据转发
     *
     */
    public class CommonJsonCallback implements Callback {
    
        /**
         * the logic layer exception, may alter in different app
         */
        protected final String RESULT_CODE = "ecode"; // 有返回则对于http请求来说是成功的,但还有可能是业务逻辑上的错误
        protected final int RESULT_CODE_VALUE = 0;
        protected final String ERROR_MSG = "emsg";
        protected final String EMPTY_MSG = "";
        protected final String COOKIE_STORE = "Set-Cookie"; // decide the server it
        // can has the value of
        // set-cookie2
    
        /**
         * the java layer exception, do not same to the logic error
         */
        protected final int NETWORK_ERROR = -1; // the network relative error
        protected final int JSON_ERROR = -2; // the JSON relative error
        protected final int OTHER_ERROR = -3; // the unknow error
    
        /**
         * 将其它线程的数据转发到UI线程
         */
        private Handler mDeliveryHandler;
        private DisposeDataListener mListener;
        private Class<?> mClass;
    
        public CommonJsonCallback(DisposeDataHandle handle) {
            this.mListener = handle.mListener;
            this.mClass = handle.mClass;
            this.mDeliveryHandler = new Handler(Looper.getMainLooper());
        }
    
        @Override
        public void onFailure(final Call call, final IOException ioexception) {
            /**
             * 此时还在非UI线程,因此要转发
             */
            mDeliveryHandler.post(new Runnable() {
                @Override
                public void run() {
                    //接口回调    到主线程
                    mListener.onFailure(new OkHttpException(NETWORK_ERROR, ioexception));
                }
            });
        }
    
        @Override
        public void onResponse(final Call call, final Response response) throws IOException {
            final String result = response.body().string();
            final ArrayList<String> cookieLists = handleCookie(response.headers());
            mDeliveryHandler.post(new Runnable() {
                @Override
                public void run() {
                    handleResponse(result);
                    /**
                     * handle the cookie
                     */
                    if (mListener instanceof DisposeHandleCookieListener) {
                        ((DisposeHandleCookieListener) mListener).onCookie(cookieLists);
                    }
                }
            });
        }
    
        private ArrayList<String> handleCookie(Headers headers) {
            ArrayList<String> tempList = new ArrayList<String>();
            for (int i = 0; i < headers.size(); i++) {
                if (headers.name(i).equalsIgnoreCase(COOKIE_STORE)) {
                    tempList.add(headers.value(i));
                }
            }
            return tempList;
        }
    
    
        /*
        处理服务器返回的数据
         */
    
        private void handleResponse(Object responseObj) {
    
            if (responseObj == null || responseObj.toString().trim().equals("")) {
                mListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
                return;
            }
    
            try {
                /**
                 * 协议确定后看这里如何修改
                 */
                JSONObject result = new JSONObject(responseObj.toString());
                if (mClass == null) {
                    //不需要解析,回调到应用层
                    mListener.onSuccess(result);
                } else {
                    //将json数据解析为java对象返回到应用层
                                 //ResponseEntityToModule   自定义的json数据解析类,这里可以使用gson,fastjson等
                    Object obj = ResponseEntityToModule.parseJsonObjectToModule(result, mClass);
                    if (obj != null) {
                        mListener.onSuccess(obj);
                    } else {
                        //json不合法
                        mListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
                    }
                }
            } catch (Exception e) {
                //其他异常
                mListener.onFailure(new OkHttpException(OTHER_ERROR, e.getMessage()));
                e.printStackTrace();
            }
        }
    }
    
    

    其实到这块
    OKhttp的底层已经封装完成了。
    为了降低耦合,我们可以在应用层在封装一下

    应用层在封装一下

    import com.youdu.module.course.BaseCourseModel;
    import com.youdu.module.recommand.BaseRecommandModel;
    import com.youdu.module.update.UpdateModel;
    import com.youdu.module.user.User;
    import com.youdu.okhttp.CommonOkHttpClient;
    import com.youdu.okhttp.listener.DisposeDataHandle;
    import com.youdu.okhttp.listener.DisposeDataListener;
    import com.youdu.okhttp.listener.DisposeDownloadListener;
    import com.youdu.okhttp.request.CommonRequest;
    import com.youdu.okhttp.request.RequestParams;
    
    /**
     * @author: vision
     * @function:
     */
    public class RequestCenter {
    
        //根据参数发送所有post请求
        public static void postRequest(String url, RequestParams params, DisposeDataListener listener, Class<?> clazz) {
            CommonOkHttpClient.get(CommonRequest.
                    createGetRequest(url, params), new DisposeDataHandle(listener, clazz));
        }
    
        /**
         * 用户登陆请求
         *
         * @param listener
         * @param userName
         * @param passwd
         */
        public static void login(String userName, String passwd, DisposeDataListener listener) {
    
            RequestParams params = new RequestParams();
            params.put("mb", userName);
            params.put("pwd", passwd);
            RequestCenter.postRequest(HttpConstants.LOGIN, params, listener, User.class);
        }
    
        /**
         * 应用版本号请求
         *
         * @param listener
         */
        public static void checkVersion(DisposeDataListener listener) {
            RequestCenter.postRequest(HttpConstants.CHECK_UPDATE, null, listener, UpdateModel.class);
        }
    
        public static void requestRecommandData(DisposeDataListener listener) {
            RequestCenter.postRequest(HttpConstants.HOME_RECOMMAND, null, listener, BaseRecommandModel.class);
        }
    
        public static void downloadFile(String url, String path, DisposeDownloadListener listener) {
            CommonOkHttpClient.downloadFile(CommonRequest.createGetRequest(url, null),
                    new DisposeDataHandle(listener, path));
        }
    
        /**
         * 请求课程详情
         *
         * @param listener
         */
        public static void requestCourseDetail(String courseId, DisposeDataListener listener) {
            RequestParams params = new RequestParams();
            params.put("courseId", courseId);
            RequestCenter.postRequest(HttpConstants.COURSE_DETAIL, params, listener, BaseCourseModel.class);
        }
    }
    
    

    http地址:

    public class HttpConstants {
    
        private static final String ROOT_URL = "http://imooc.com/api";
    
        /**
         * 请求本地产品列表
         */
        public static String PRODUCT_LIST = ROOT_URL + "/fund/search.php";
    
        /**
         * 本地产品列表更新时间措请求
         */
        public static String PRODUCT_LATESAT_UPDATE = ROOT_URL + "/fund/upsearch.php";
    
        /**
         * 登陆接口
         */
        public static String LOGIN = ROOT_URL + "/user/login_phone.php";
    
        /**
         * 检查更新接口
         */
        public static String CHECK_UPDATE = ROOT_URL + "/config/check_update.php";
    
        /**
         * 首页产品请求接口
         */
        public static String HOME_RECOMMAND = ROOT_URL + "/product/home_recommand.php";
    
        /**
         * 课程详情接口
         */
        public static String COURSE_DETAIL = ROOT_URL + "/product/course_detail.php";
    
    }
    
    
    

    具体的使用看一下:

        //发送推荐产品请求
        private void requestRecommandData() {
            RequestCenter.requestRecommandData(new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mRecommandData = (BaseRecommandModel) responseObj;
                    //更新UI
                    showSuccessView();
                }
    
                @Override
                public void onFailure(Object reasonObj) {
                    //显示请求失败View
                    showErrorView();
                }
            });
        }
    
    
    展开全文
  • okhttp3封装工具

    2017-01-16 16:45:17
    项目需导入okhttp-3.2.0.jar和okio-1.11.0.jar两个jar包才可运行 如果不导入okio-1.11.0.jar包则会抛异常
  • Okhttp3进行二次封装,对外提供了POST请求、GET请求、PATCH请求、PUT请求、DELETE请求、上传文件、下载文件、取消请求、Raw/Json/Gson返回、后台下载管理等功能
  • 此网络请求封装基于 RxJava + Retrofit + okHttp3,里面包含使用文档。可适用于所有 json 数据返回的网络请求,包括多文件上传,默认适用Gson解析返回结果,支持自定义解析对象,支持自定义解析方式。
  • 基于OkHttp3封装的网络请求库 功能点 支持Http/Https协议/自定义Https证书认证 支持同步/异步请求 支持异步延迟执行 支持Post/Get/Put/Delete请求 支持Cookie持久化,支持Gzip压缩 支持协议头参数Head设置 支持二...
  • 请关注我最新的架构模式 基于Rx-Mvp全方位升级Rx-Mvp 项目包含两个部分功能/模块RHttp : 基于 RxJava2 + Retrofit2 + OkHttp3 + RxLifecycle2 框架整合封装的网络请求框架MVP : MVC 框架的升级版本,通过 Presenter ...
  • okhttp框架封装

    2018-04-10 16:16:18
    一个良好的http请求框架的封装,支持接口的链式请求,能够更加灵便的使用
  • okhttp3封装

    2019-07-10 00:40:05
    https://github.com/hongyangAndroid/okhttputils 此处借鉴鸿洋大神分享的框架:https://github.com/hongyangAndroid/okhttputils 还有鸿洋大神的博客:... 使用前导入: ... ​​​​​​Okhttp3封装_Snow_I.

    第三方封装:

    ​
     https://github.com/hongyangAndroid/okhttputils
    
    此处借鉴鸿洋大神分享的框架:https://github.com/hongyangAndroid/okhttputils
    
    还有鸿洋大神的博客:https://blog.csdn.net/lmj623565791/article/details/47911083
    
    使用前导入:
    
    implementation 'com.zhy:okhttputils:2.6.2'
    
    ​​​​​​Okhttp3封装_Snow_Ice_Yang的博客-CSDN博客_okhttp3封装
    
    ​

    自己封装一:

    package com.jiuddata.common.utils;
    
    import okhttp3.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.Map;
    
    /**
     * http通信服务封装
     *
     * @author:debug
     */
    public class HttpService {
     
        private static final Logger log = LoggerFactory.getLogger(HttpService.class);
     
        private OkHttpClient client = new OkHttpClient();
    
    /*
    使用
      Map<String, String> headerMap=new HashMap<>();
                headerMap.put("Content-Type","application/json");
                Map<String, String> bodyParams=new HashMap<>();
                bodyParams.put("images_path","E:/python_project/images/scottsdale");
                bodyParams.put("out_put","E:/python_project/images/scottsdale/a.jpg");
                bodyParams.put("v5put","E:/python_project/images/scottsdale");
                HttpService httpService = new HttpService();
                String post = httpService.post("http://192.168.0.24:8082/image_fusion", headerMap,
                        "application/json",JSON.toJSONString(bodyParams));
                System.err.println(post);
    */
    //    /**
    //     * OkHttpClient调用dubboOne的服务提供的http协议
    //     */
    //    private OkHttpClient httpClient=new OkHttpClient();
    //
    //    @Autowired
    //    private ObjectMapper objectMapper;
    //    /**
    //     * 去请求dubboOnew的server中的text3接口
    //     * @param user
    //     */
    //    public void pushOrder(User user){
    //        try {
    //            //构造builder
    //            Request.Builder builder=new Request.Builder()
    //                    .url("http://127.0.0.1:9013/v1/record/text3")
    //                    .header("Content-Type","application/json");
    //            //构造请求体
    //            RequestBody requestBody= RequestBody.create(MediaType.parse("application/json"),
    //                    objectMapper.writeValueAsString(user));
    //            //构造请求
    //            Request request=builder.post(requestBody).build();
    //            //发起请求
    //            Response response=httpClient.newCall(request).execute();
    //        }catch (Exception e){
    //            e.printStackTrace();
    //        }
    //    }
        /**
         * 构造通用的get-request
         *
         * @param url       请求路径
         * @param headerMap 请求头key-value
         * @return
         * @throws Exception
         */
        private Request commonGetRequest(String url, Map<String, String> headerMap) throws Exception {
            Request.Builder builder = new Request.Builder();
     
            Request request;
            if (headerMap != null && headerMap.keySet() != null && headerMap.keySet().size() > 0) {
                Headers headers = Headers.of(headerMap);
                request = builder.get()
                        .url(url)
                        .headers(headers)
                        .build();
            } else {
                request = builder.get()
                        .url(url)
                        .build();
            }
            return request;
        }
     
        private Request.Builder commonPostBuilder(String url, Map<String, String> headerMap) throws Exception {
            Request.Builder builder;
            if (headerMap != null && headerMap.keySet() != null && headerMap.keySet().size() > 0) {
                Headers headers = Headers.of(headerMap);
                builder = new Request.Builder()
                        .url(url)
                        .headers(headers);
            } else {
                builder = new Request.Builder()
                        .url(url);
            }
            return builder;
        }
     
     
        /**
         * get请求
         *
         * @param url       请求url
         * @param headerMap 请求头map
         * @return 结果字符串
         */
        public String get(String url, Map<String, String> headerMap) throws Exception {
            Request request = commonGetRequest(url, headerMap);
     
            Response response;
            try {
                response = client.newCall(request).execute();
                return response.body().string();
            } catch (Exception e) {
                log.error("发送同步-get请求发生异常:url={} ", e.fillInStackTrace());
            }
            return null;
        }
     
        /**
         * post请求
         *
         * @param url         请求Url
         * @param headerMap   请求头map
         * @param contentType 请求内容类型
         * @param data        请求体数据-对象序列化后的字符串格式数据
         * @return 结果字符串
         */
        public String post(String url, Map<String, String> headerMap, String contentType, String data) throws Exception {
            Request.Builder builder = commonPostBuilder(url, headerMap);
     
            Request request;
            RequestBody requestBody;
            if (data!=null && contentType!=null) {
                requestBody = RequestBody.create(MediaType.parse(contentType), data);
                request = builder.post(requestBody).build();
            } else {
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                request = builder.post(bodyBuilder.build()).build();
            }
     
            Response response;
            try {
                response = client.newCall(request).execute();
                return response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
     
     
        /**
         * post请求--无请求体
         *
         * @param url 请求Url
         * @return 结果字符串
         */
        public String post(String url) throws Exception {
            Request.Builder builder = new Request.Builder().url(url);
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            Request request = builder.post(bodyBuilder.build()).build();
     
            Response response;
            try {
                response = client.newCall(request).execute();
                return response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
     
     
        /**
         * post请求
         *
         * @param url
         * @param headerMap
         * @param bodyParams 请求体数据-map格式
         * @return
         * @throws Exception
         */
        public String post(String url, Map<String, String> headerMap, Map<String, String> bodyParams) throws Exception {
            Request.Builder builder = commonPostBuilder(url, headerMap);
     
            RequestBody body = setRequestBody(bodyParams);
            Request request = builder
                    .post(body)
                    .url(url)
                    .build();
     
            Response response;
            try {
                response = client.newCall(request).execute();
                return response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
     
        /**
         * post请求
         *
         * @param params
         * @return 备注:form表单提交
         */
        private RequestBody setRequestBody(Map<String, String> params) {
            RequestBody body = null;
            FormBody.Builder formBuilder = new FormBody.Builder();
            if (params != null && params.keySet() != null && params.keySet().size() > 0) {
                String key;
                Iterator<String> iterator = params.keySet().iterator();
                while (iterator.hasNext()) {
                    key = iterator.next().toString();
                    formBuilder.add(key, params.get(key));
                }
            }
            body = formBuilder.build();
     
            return body;
        }
     
        /**
         * 
         * @param url
         * @param params 参数
         * @param headMap 请求头
         * @return
         */
        public static String httpGet(String url, Map<String, Object> params, Map<String, String> headMap) {
            // 设置HTTP请求参数
            String result = null;
            url += getParams(params);
            String string=null;
            Headers setHeaders = SetHeaders(headMap);
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).headers(setHeaders).build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                string = response.body().string();
            } catch (Exception e) {
                log.error("调用三方接口出错", e);
            }
            return string;
        }
    
        public static String getParams(Map<String, Object> params) {
            StringBuffer sb = new StringBuffer("?");
            if (params.size()>0) {
                for (Map.Entry<String, Object> item : params.entrySet()) {
                    Object value = item.getValue();
                    if (value!=null&&value!="") {
                        sb.append("&");
                        sb.append(item.getKey());
                        sb.append("=");
                        sb.append(value);
                    }
                }
                return sb.toString();
            } else {
                return "";
            }
        }
    
        public static Headers SetHeaders(Map<String, String> headersParams) {
            Headers headers = null;
            okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
            if (headersParams.size()>0) {
                Iterator<String> iterator = headersParams.keySet().iterator();
                String key = "";
                while (iterator.hasNext()) {
                    key = iterator.next().toString();
                    headersbuilder.add(key, headersParams.get(key));
                }
            }
            headers = headersbuilder.build();
            return headers;
        }
    
    }
    

    调用

    @RequestMapping("/getText3")
        public String getText(String name,String password){
            User user = new User(name, password);
    
    
            try {
                //去调用的dubbo中server服务的http测试接口路径
                String url="http://127.0.0.1:9013/v1/record/text3";
                java.util.Map<String,String> headerMap=new HashMap<>();
                //参数类型,我接口提供者接受的是json
                headerMap.put("Content-Type","application/json");
                HttpService httpService = new HttpService();
                String res = httpService.post(url,headerMap,"application/json"
                        ,objectMapper.writeValueAsString(user));
    
                log.info("响应结果:{} ",res);
                return res;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
    
    <!-- okhttp -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>3.1.2</version>
    </dependency>

    2021-11-22封装二:

    package com.weiguanjishu.common;
    
    import lombok.extern.slf4j.Slf4j;
    import okhttp3.*;
    import okhttp3.Request.Builder;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.security.SecureRandom;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    
    
    /**
     * @author tiger
     */
    /*
    
      <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.10.0</version>
            </dependency>
        使用如:        
            String url = "http://www.csdn.net/";
            Map<String, String> headers=new HashMap<>();
            Map<String, String> params=new HashMap<>();
            OkHttpUtil.httpGet(url,headers,params);
    
    */
    
    @Slf4j
    public class OkHttpUtil {
    
        private static OkHttpUtil instance;
        private static OkHttpClient client;
    
        private static MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");
        private static MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
    
        private static final Integer connTimeout = 10000;
        private static final Integer readTimeout = 10000;
        private static final Integer writeTime = 20000;
    
        static {
            client = new OkHttpClient.Builder()
                    .connectTimeout(connTimeout, TimeUnit.MILLISECONDS)
                    .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                    .writeTimeout(writeTime, TimeUnit.MILLISECONDS)
                    .sslSocketFactory(createSslSocketFactory(), x509TrustManager())
                    .connectionPool(createConnectionPool())
                    .build();
        }
    
        public static OkHttpUtil getInstance() {
    
            if (instance == null) {
                instance = new OkHttpUtil();
            }
    
            return instance;
        }
    
        /**
         * 设置连接池
         * 1.最大等待连接数
         * 2.连接时间
         */
        private static ConnectionPool createConnectionPool() {
            return new ConnectionPool(400, 5000, TimeUnit.MILLISECONDS);
        }
    
    
        /**
         * 信任所有证书
         */
        private static X509TrustManager x509TrustManager() {
            return new 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];
                }
            };
    
        }
    
        /**
         * HTTPS证书验证套接字工厂
         */
        private static SSLSocketFactory createSslSocketFactory() {
            SSLSocketFactory sslSocketFactory = null;
            try {
                // 信任所有链接
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
                sslSocketFactory = sslContext.getSocketFactory();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sslSocketFactory;
        }
    
        /***
         *  Get请求
         */
        public static String httpGet(String url, Map<String, String> headers, Map<String, String> params) {
            Response response = null;
            String res = "";
            log.info("[HttpGet start] URL:{}", url);
            if (url == null || url.isEmpty()) {
                throw new RuntimeException("请求地址不能为空");
            }
    
            StringBuffer buffer = new StringBuffer(url);
            Builder builder = new Builder();
    
            try {
                // 添加header
                if (headers != null && !headers.isEmpty()) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        builder.addHeader(entry.getKey(), entry.getValue());
                    }
                }
    
                // 请求参数
                if (params != null && !params.isEmpty()) {
                    boolean flag = true;
                    Iterator iterator = params.entrySet().iterator();
    
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
    
                        if (flag) {
                            buffer.append("?" + entry.getKey() + "=" + entry.getValue());
                            flag = false;
                        } else {
                            buffer.append("&" + entry.getKey() + "=" + entry.getValue());
                        }
                    }
                }
    
                log.info("[HttpGet start] URL:{}", buffer);
                Request request = builder.url(buffer.toString()).get().build();
                log.info("[HttpGet finish] URL:{}", request);
                response = client.newCall(request).execute();
                res = response.body().string();
            } catch (IOException var1) {
                log.error("[HttpGet Exception] URL:{}, error:{}", url, var1);
                throw new RuntimeException(var1);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            return res;
        }
    
        /***
         *  POST  form表单请求
         */
        public static String postForm(String url, Map<String, String> headers, Map<String, String> params) {
            log.info("[HttpPost start] URL:{}", url);
    
            FormBody.Builder formBody = new FormBody.Builder();
            String result = null;
    
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    formBody.add(key, params.get(key));
                }
            }
            RequestBody body = formBody.build();
            Builder request = new Builder();
            request.url(url).addHeader("CONTENT_TYPE", FORM_TYPE.toString()).build();
    
            // 添加请求头参数
            if (headers != null && !headers.isEmpty()) {
                Iterator iterator = headers.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }
    
            Request r = request.post(body).build();
            Response response = null;
            try {
                response = client.newCall(r).execute();
                ResponseBody responseBody = response.body();
    
                result = responseBody.string();
                log.info("[HttpPost FORM FINISH] RESULT: {}", result);
            } catch (IOException var2) {
                log.error("[HttpPost FORM Exception] URL:{}, error:{}", url, var2);
                throw new RuntimeException(var2);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            return result;
        }
    
        /***
         *  POST JSON 请求,自定义超时配置
         */
        public static Response postForm(String url, String message, Map<String, String> headers) {
            return httpPost(url, message, headers, 5000, 5000, 5000);
        }
    
    
        public static Response httpPost(String url, String message, Map<String, String> headers, Integer connTimeout, Integer readTimeout, Integer writeTime) {
            RequestBody body = RequestBody.create(JSON_TYPE, message);
            Builder builder = new Builder();
            builder.url(url).post(body).addHeader("Accept", "application/json").build();
    
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> header : headers.entrySet()) {
                    builder.addHeader(header.getKey(), header.getValue());
                }
            }
            Request request = builder.build();
            OkHttpClient client = new OkHttpClient.Builder().connectTimeout(connTimeout, TimeUnit.MILLISECONDS).readTimeout(readTimeout, TimeUnit.MILLISECONDS).writeTimeout(writeTime, TimeUnit.MILLISECONDS).build();
            try {
                Response response = client.newCall(request).execute();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
    
        /***
         *  POST JSON 请求
         */
        public static String post(String url, String message, Map<String, String> headers) {
            RequestBody requestBody = RequestBody.create(JSON_TYPE, message);
            Builder builder = new Builder();
            builder.url(url).post(requestBody).build();
            Response response = null;
            String result = "";
            try {
                // 添加header
                if (headers != null && !headers.isEmpty()) {
                    Iterator iterator = headers.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        builder.addHeader((String) entry.getKey(), (String) entry.getValue());
                    }
                }
                Request request = builder.build();
                response = client.newCall(request).execute();
                if (response.code() == 200) {
                    result = response.body() == null ? "" : response.body().string();
                }
    
    
            } catch (IOException var3) {
                log.error("[HttpPost JSON Exception] URL:{}, error:{}", url, var3);
                throw new RuntimeException(var3);
    
            } finally {
                if (response != null) {
                    response.close();
                }
            }
    
            return result;
        }
    
    }
    

    2022-4-2原生用法:

    简单使用方法:
    首先,如果要设置设置超时时间和缓存,要通过OkHttpClient.Builder来设置

    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
    OkHttpClient okHttpClient=builder.build();

    get请求:

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
        .url(url)
        .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 {
    		System.out.println(response.body().string());
                }
            });

    response的body有很多种输出方法,string()只是其中之一,注意是string()不是toString()。如果是下载文件就是response.body().bytes()。
    另外可以根据response.code()获取返回的状态码。
    post请求:
    post提交普通的表单:如登录.

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
        .add("键", "值")
        .add("键", "值")
        .build();
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {...}

    RequestBody的数据格式都要指定Content-Type,常见的有三种:
    application/x-www-form-urlencoded 数据是个普通表单
    multipart/form-data 数据里有文件
    application/json 数据是个json
    上边的普通表单并没有指定Content-Type,这是因为FormBody继承了RequestBody,它已经指定了数据类型为application/x-www-form-urlencoded。

    post提交json数据:

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody body = RequestBody.create(JSON, "你的json数据");
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {...}
    post上传文件:
    先定义上传文件类型:
    
    public static final MediaType MEDIA_TYPE_MARKDOWN
                = MediaType.parse("text/x-markdown; charset=utf-8");
     
    OkHttpClient okHttpClient = new OkHttpClient();
     File file = new File("/sdcard/xxx.txt");
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                    .build();
    call.enqueue(new Callback() {...}

    post上传文件并传入其他类型的字段:

    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
    OkHttpClient okHttpClient = new OkHttpClient();
     File file = new File("/sdcard/xxx.txt");
    RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("token","token")
                .addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                .build();
    Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
    call.enqueue(new Callback() {...}

    异步下载:

    	OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
     
                }
     
                @Override
                public void onResponse(Call call, Response response) {
                    InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(new File("/sdcard/xx.txt"));
                        byte[] buffer = new byte[2048];
                        int len = 0;
                        while ((len = inputStream.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0, len);
                        }
                        fileOutputStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                   }
               }
           });

    上面的都为异步请求,当然也支持同步的方式,同步的只要调用 call.execute()就可以了。

    okhttp3的简单封装:

    public class OkHttpClientManager {
        private static OkHttpClientManager mInstance;
        private OkHttpClient mOkHttpClient;
        private Handler mDelivery;
        private Gson mGson;
     
        private OkHttpClientManager()
        {
             OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
    	okHttpClient.connectTimeout(5, TimeUnit.SECONDS);
            okHttpClient.readTimeout(5, TimeUnit.SECONDS);
            okHttpClient.cookieJar(new CookieJar() {
                private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    cookieStore.put(url, cookies);
                }
     
                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    return null;
                }
            });
            mOkHttpClient=okHttpClient.build();
            mDelivery = new Handler(Looper.getMainLooper());
            mGson = new Gson();
        }
     
        public static OkHttpClientManager getInstance()
        {
            if (mInstance == null)
            {
                synchronized (OkHttpClientManager.class)
                {
                    if (mInstance == null)
                    {
                        mInstance = new OkHttpClientManager();
                    }
                }
            }
            return mInstance;
        }
     
         /**
         * 异步的get请求
         *
         * @param url
         * @param callback
         */
        private void _getAsyn(String url, final ResultCallback callback)
        {
            final Request request = new Request.Builder()
                    .url(url)
                    .build();
            deliveryResult(callback, request);
        }
     
        /**
         * 异步的post请求
         *
         * @param url
         * @param callback
         * @param params
         */
        private void _postAsyn(String url, final ResultCallback callback, Param... params)
        {
            Request request = buildPostRequest(url, params);
            deliveryResult(callback, request);
        }
     
        /**
         * 异步的post请求
         *
         * @param url
         * @param callback
         * @param params
         */
        private void _postAsyn(String url, final ResultCallback callback, Map<String, String> params)
        {
            Param[] paramsArr = map2Params(params);
            Request request = buildPostRequest(url, paramsArr);
            deliveryResult(callback, request);
        }
     
     private Param[] map2Params(Map<String, String> params)
        {
            if (params == null) return new Param[0];
            int size = params.size();
            Param[] res = new Param[size];
            Set<Map.Entry<String, String>> entries = params.entrySet();
            int i = 0;
            for (Map.Entry<String, String> entry : entries)
            {
                res[i++] = new Param(entry.getKey(), entry.getValue());
            }
            return res;
        }
     
     //*************对外公布的方法************
     
        //异步get请求
        public static void getAsyn(String url, ResultCallback callback)
        {
            getInstance()._getAsyn(url, callback);
        }
        //异步的post请求
        public static void postAsyn(String url, final ResultCallback callback, Param... params)
        {
            getInstance()._postAsyn(url, callback, params);
        }
     
        //异步的post请求
        public static void postAsyn(String url, final ResultCallback callback, Map<String, String> params)
        {
            getInstance()._postAsyn(url, callback, params);
        }
     
    private void deliveryResult(final ResultCallback callback, Request request)
        {
            mOkHttpClient.newCall(request).enqueue(new Callback()
            {
     
                @Override
                public void onFailure(Call call, IOException e) {
                    sendFailCallback(callback,e);
                }
     
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try
                    {
                        final String string = response.body().string();
                        if (callback.mType == String.class)
                        {
                            sendSuccessCallBack(callback,string);
                        } else
                        {
                            Object o = mGson.fromJson(string, callback.mType);
                            sendSuccessCallBack(callback,string);
                        }
     
                    } catch (IOException e)
                    {
                        sendFailCallback(callback,e);
                    } catch (com.google.gson.JsonParseException e)//Json解析的错误
                    {
                        sendFailCallback(callback,e);
                    }
                }
            });
        }
    private void sendFailCallback(final ResultCallback callback, final Exception e) {
            mDelivery.post(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onFailure(e);
                    }
                }
            });
        }
     
        private void sendSuccessCallBack(final ResultCallback callback, final Object obj) {
            mDelivery.post(new Runnable() {
                @Override
                public void run() {
                    if (callback != null) {
                        callback.onSuccess(obj);
                    }
                }
            });
        }
     
        private Request buildPostRequest(String url, Param[] params)
        {
            if (params == null)
            {
                params = new Param[0];
            }
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            for (Param param : params)
            {
                formBodyBuilder.add(param.key, param.value);
            }
            RequestBody requestBody = formBodyBuilder.build();
            return new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
        }
    public static abstract class ResultCallback<T>
        {
            Type mType;
     
            public ResultCallback()
            {
                mType = getSuperclassTypeParameter(getClass());
            }
     
            static Type getSuperclassTypeParameter(Class<?> subclass)
            {
                Type superclass = subclass.getGenericSuperclass();
                if (superclass instanceof Class)
                {
                    throw new RuntimeException("Missing type parameter.");
                }
                ParameterizedType parameterized = (ParameterizedType) superclass;
                return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
            }
     
            /**
             * 请求成功回调
             * @param response
             */
            public abstract void onSuccess(T response);
     
            /**
             * 请求失败回调
             * @param e
             */
            public abstract void onFailure(Exception e);
        }
     
        /**
         * post请求参数类
         */
        public static class Param
        {
            public Param()
            {
            }
     
            public Param(String key, String value)
            {
                this.key = key;
                this.value = value;
            }
            String key;
            String value;
        }
     
    }

    展开全文
  • 简单封装使用OkHttp3

    2017-06-30 11:36:09
    简单封装使用OkHttp3
  • Java封装OkHttp3工具类

    2021-07-06 13:55:24
    本文来说下Java封装OkHttp3工具类 文章目录概述 概述
  • Android OkHttp的简单使用和封装详解 1,昨天把okHttp仔细的看了一下,以前都是调用同事封装好了的网络框架,直接使用很容易,但自己封装却不是那么简单,还好,今天就来自我救赎一把,就和大家写写从最基础的OKHttp...
  • Android okhttp3封装

    千次阅读 2017-12-07 11:30:37
    Okhttp确实是功能强大,高效率,简洁的网络请求框架,所以最近项目也集成了改框架,写了一个Manager管理类,整理下给大家看下。*** * 使用OkHttp框架执行网络请求 * */public class OkHttpManager { private ...
  • 简单封装okhttp3请求框架
  • 很火的Retrofit2+RxJava2+OkHttp3网络请求框架,功能强大,结构合理,使用简单方便。后面还会给大家发自己整理过的Retrofit和RxJava、RxAndroid和RxBus。
  • OKHttp网络请求封装

    2017-10-25 16:58:47
    在开发过程中有时候一个项目可能会用两三个网络请求框架,使用自己的规范来封装三方库。我这是封装OKHttp实现该接口,当然你也可以使用别的三方库来实现在接口。
  • OkHttp简单封装

    千次阅读 2022-04-10 14:30:21
    简单封装OkHttp框架,单例模式。一句话即可使用。 返回值已进行JSON转换,拿到响应数据后的回调运行在主线程,可以直接修改UI。 已写get请求、form表单post请求,后续再添加。 依赖 //OkHttp implementation '...
  • OkHttpUtils// .get()// .url(url)// .build()// .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "gson-2.2.1.jar")// { @Override public void inProgress...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 22,684
精华内容 9,073
关键字:

okhttp3封装