美文网首页
OkHttp3的简单使用

OkHttp3的简单使用

作者: 王魔王 | 来源:发表于2018-11-13 21:04 被阅读0次

    网络上有关OkHttp3的文章多如牛毛,优秀的文章也不胜其数。
    为什么要写这一篇文章呢?本篇的目的在于提供一种简单的,能满足常见功能即可的迷你二次封装
    言归正传:此篇适合伸手党,就是那种别跟我说什么底层原理,框架内核,敲代码就是一把梭哈!!!复制粘贴党,拿起键盘就是干的程序员。

    一、定义OkHttpUtil工具类

    其实就是一个普通的java类,其中有一些全局变量。

    public class OkHttpUtil {
        private static Gson gson = new Gson();
        private static final String MEDIA_TYPE = "application/json; charset=utf-8";
        private static final String METHOD_GET = "GET";
        private static final String METHOD_POST = "POST";
        private static final String METHOD_PUT = "PUT";
        private static final String METHOD_DELETE = "DELETE";
        private static OkHttpClient okHttpClient;
    
    
        /**
         * 私有化构造方法
         * 使用单利模式
         */
        private OkHttpUtil() {}
    

    二、定义OkhttpUtil的init方法

    这个init()方法是让我们在项目的初始化时候调用的,作用是实利化OkHttpClient对象,传入公共的请求头参数。

      public static void init(Map headers) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.readTimeout(3000, TimeUnit.MILLISECONDS);
            builder.writeTimeout(3000, TimeUnit.MILLISECONDS);
            builder.connectTimeout(3000, TimeUnit.MILLISECONDS);
            builder.addInterceptor(new OKHeaderInterceptor(headers));//添加请求头,此行代码可以不添加
            builder.addInterceptor(new OkLogInterceptor());//添加log日志,此行代码可以不添加
            okHttpClient = builder.build();
        }
    

    三、封装创建request对象的方法

      /**
         * 创建request对象
         *
         * @param url
         * @param method
         * @param baseRequest 项目中自己的的baseRequest对象
         * @return
         */
        private static  Request createRequest(String url, String method, BaseRequest baseRequest) {
            RequestBody requestBody = null;
            if (baseRequest != null) {
                String bodyJson = gson.toJson(baseRequest);
                MediaType JSON = MediaType.parse(MEDIA_TYPE);
                requestBody = RequestBody.create(JSON, bodyJson);
            }
    
            Request.Builder builder = new Request.Builder().url(url);
    
            Request request = null;
    
            switch (method) {
                case METHOD_GET:
                    request = builder.build();
                    break;
                case METHOD_POST:
                    request = builder.post(requestBody).build();
                    break;
                case METHOD_PUT:
                    if (requestBody != null) {
                        request = builder.put(requestBody).build();
                    }
                    break;
                case METHOD_DELETE:
                    if (requestBody != null) {
                        request = builder.delete(requestBody).build();
                    } else {
                        request = builder.delete().build();
                    }
                    break;
            }
    
            return request;
        }
    

    四、封装常见的get和post方法

    
        /**
         * 异步post方法
         *
         * @param url
         * @param baseRequest
         * @param callback
         */
        public static void enqueuePost(String url, BaseRequest baseRequest, Callback callback) {
    
            Request request = createRequest(url, METHOD_POST, baseRequest);
            Call call = okHttpClient.newCall(request);
            call.enqueue(callback);
    
        }
    
    
        /**
         * 异步get方法
         *
         * @param url
         * @param callback
         */
        public static  void enqueueGet(String url, Callback callback) {
            Request request = createRequest(url, METHOD_GET, null);
            Call call = okHttpClient.newCall(request);
            call.enqueue(callback);
    
        }
    
    
        /**
         * 同步post方法
         * 注意此方法不能在主线程中调用
         *
         * @param url
         */
        public  static Response executePost(String url, BaseRequest baseRequest) throws IOException {
            Request request = createRequest(url, METHOD_POST, baseRequest);
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            return response;
        }
    
        /**
         * 同步get方法
         * 注意此方法不能在主线程中调用
         *
         * @param url
         */
        public  static Response executeGet(String url) throws IOException {
            Request request = createRequest(url, METHOD_GET, null);
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            return response;
        }
    

    五、使用方式

    首先要在项目的application中调用init方法
    首先要在项目的application中调用init方法
    首先要在项目的application中调用init方法
    
            String url = "http://www.baidu.com";
            OkHttpUtil.enqueueGet(url, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                    //注意此方法返回在子线程中
    
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //注意此方法返回在子线程中
                    //获取http 响应码
                    int code = response.code();
    
                    //获取服务器返回的json数据
                    ResponseBody body = response.body();
                    String jsonData = body.string();
    
                    //获取本次请求的请求参数
                    //request中有一切请求参数,例如本次请求的url
                    Request request = response.request();
                    HttpUrl requestUrl = request.url();
    
                }
            });
    

    OkLogInterceptor的代码

    
    /**
     * okhttp3 的日志拦截器
     *这个拦截器的主要功能是让我们提供请求参数日志的打印
     */
    public class OkLogInterceptor implements Interceptor {
    
    
        @Override
        public Response intercept(Chain chain) throws IOException {
    
            Request request = chain.request();
    
            String method = request.method();
            HttpUrl url = request.url();
            LogUtil.d("本次请求", "ulr:" + url.toString() + "  method:" + method);
    
            Headers headers = request.headers();
            Set<String> names = headers.names();
            Iterator<String> iterator = names.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                String value = headers.get(next);
                LogUtil.d(next + ":" + value);
            }
            return chain.proceed(request);
        }
    }
    

    OKHeaderInterceptor代码

    
    /**
     * okhttp3的请求头拦截器
     * 这个里面主要的功能是让我们添加公共的请求头
     */
    public class OKHeaderInterceptor implements Interceptor {
        private Map<String, String> headers;
    
        public OKHeaderInterceptor(Map headers) {
            if (headers != null) {
    
                this.headers = headers;
            }
        }
    
        @Override
        public Response intercept(Chain chain) throws IOException {
    
            Request request = chain.request();
            Request.Builder builder = request.newBuilder();
            if (headers != null) {
                Set set = headers.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    builder.addHeader(next, headers.get(next));
                }
            }
            request = builder.build();
            return chain.proceed(request);
        }
    }
    

    相关文章

      网友评论

          本文标题:OkHttp3的简单使用

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