Java中常用的HTTP客户端库:OkHttp和HttpClient(包含请求示例代码)

大家好,今天小编来分享一下工作中常用到的两种HTTP客户端库(OkHttpHttpClient),它们在使用、性能和功能等方面有一些显著的区别。接下来,我会通过实际的代码示例,展示如何使用这些库进行HTTP请求和处理响应。希望接下来的内容,对大家的学习和工作带来帮助。

 一、OkHttp简介

1、使用方式

  • OkHttp是由Square公司开发的高性能HTTP客户端,专为现代用于设计,支持 Android 和 Java 平台,支持HTTP/2、连接池、透明的GZIP压缩、拦截器等功能。
  • 使用OkHttp发送请求通常需要创建OkHttpClient对象,然后创建Request对象,最后通过Call对象执行请求。

2、性能

  • OkHttp在非单例模式下性能更好,因为它使用了连接池和透明的GZIP压缩,减少了请求延时和响应数据的大小。
  • OkHttp同时支持同步和异步请求,异步请求使用enqueue方法

3、适用场景

  • 适用于Android应用开发,尤其是需要高性能和简洁API的场景,也可以应用到java应用中。

4、使用OkHttp发送GET和POST请求

(1)使用OkHttp发送GET请求示例代码

/**
     * 通过OkHttp客户端进行Get请求
     * @param url
     * @return
     */
    public static String getByOkHttp(String url) {

        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();

        //创建请求
        Request request = new Request.Builder()
                .addHeader("Authorization", "") //设置请求头,用于鉴权使用
                .url(url)
                .get()
                .build();

        //发送请求并获取响应
        try(Response response = client.newCall(request).execute()){
            if(response.isSuccessful()){
                return response.body().string();
            }else {
                throw new IOException("Unexpected code " + response.code());
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    (2)使用OkHttp发送POST请求(请求方式application/x-www-form-urlencoded)

    /**
         * 通过OkHttp客户端进行Post请求,参数格式表单形式
         */
        public static String postByOkHttp(String url) {
            //token信息,供鉴权使用
            String token = "";
    
            //创建OkHttpClient实例
            OkHttpClient client = new OkHttpClient();
    
            //创建请求体(请求参数)
            FormBody formBody = new FormBody.Builder()
                    .add("param1", "value1")
                    .add("param2", "value2")
                    .build();
    
            //创建请求
            Request request = new Request.Builder()
                    .addHeader("Authorization", token) //设置请求头,用于鉴权使用
                    .url(url)
                    .post(formBody)
                    .build();
    
            //发送请求并获取响应
            try(Response response = client.newCall(request).execute()){
                if(response.isSuccessful()){
                    return response.body().string();
                }else {
                    throw new IOException("Unexpected code " + response.code());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

    (3)使用OkHttp发送POST请求(请求方式application/json)

    //通过OkHttp客户端进行Post请求,参数格式json形式
        public static String postJsonByOkHttp(String url) {
            //token信息,供鉴权使用
            String token = "";
    
            //创建OkHttpClient实例
            OkHttpClient client = new OkHttpClient();
    
            //创建请求体(请求参数)
            RequestParam param = new RequestParam();
            param.setName("张三");
            param.setAge(18);
            String json = JSON.toJSONString(param);
    
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(mediaType, json);
    
            //创建请求
            Request request = new Request.Builder()
                    .addHeader("Authorization", token) //设置请求头,用于鉴权使用
                    .url(url)
                    .post(requestBody)
                    .build();
    
            //发送请求并获取响应
            try(Response response = client.newCall(request).execute()){
                if(response.isSuccessful()){
                    return response.body().string();
                }else {
                    throw new IOException("Unexpected code " + response.code());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

    二、HttpClient简介

    1、使用方式

    • HttpClient是Apache HttpComponents项目的一部分,提供了丰富的功能,如连接管理、认证、HTTP状态管理等。
    • 使用HttpClient发送请求通常需要创建CloseableHttpClient对象,然后创建具体的HTTP请求对象(如HttpGetHttpPost等),最后调用execute方法执行请求 。

    2、性能

    • 在单例模式下,HttpClient的响应速度较快,性能与OkHttp相差不大 
    • 在非单例模式下,HttpClient创建连接的开销较大,性能不如OkHttp 
    • 支持同步和异步请求,异步请求需要使用CloseableHttpAsyncClient

    3、适用场景

    • 适用于Java SE应用程序,尤其是需要复杂HTTP功能(如代理、认证等)的场景 

    4、使用HttpClient发送GET和POST请求

    (1)使用HttpClient发送GET请求示例代码

    /**
         * 通过HttpClient进行Get请求
         */
    
        public static String getHttpClient(String url) {
            //创建HttpClient实例
            try(CloseableHttpClient client = HttpClients.createDefault()){
                //token信息
                String token = "";
    
                //创建HttpGet请求
                HttpGet httpGet = new HttpGet(url);
    
                //设置鉴权参数
                httpGet.setHeader("Authorization", token);
    
                //发送请求并获取响应
                try(CloseableHttpResponse response = client.execute(httpGet)){
                    if(response.getStatusLine().getStatusCode() == 200){
                        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
                        return EntityUtils.toString(response.getEntity(), "UTF-8");
                    }
                }
    
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

    (2)使用HttpClient发送POST请求示例代码(访问方式application/x-www-form-urlencoded

    /**
         * 通过HttpClient进行Post请求,参数格式表单形式
         */
        public static String postFormByHttpClient(String url) {
            //创建HttpClient实例
            try(CloseableHttpClient client = HttpClients.createDefault()){
                //创建HttpPost请求
                HttpPost httpPost = new HttpPost(url);
    
                //设置鉴权参数
                String token = "";
                httpPost.setHeader("Authorization", token);
    
                //设置请求参数
                List params = new ArrayList<>();
                params.add(new BasicNameValuePair("param1", "value1"));
                params.add(new BasicNameValuePair("param2", "value2"));
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    
                //设置请求方式(表单形式)
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    
                //发送请求并获取响应
                try(CloseableHttpResponse response = client.execute(httpPost)){
                    if(response.getStatusLine().getStatusCode() == 200){
                        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
                        return EntityUtils.toString(response.getEntity(), "UTF-8");
                    }
                }
    
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

    (3)使用HttpClient发送POST请求示例代码(访问方式application/json

    /**
         * 通过HttpClient进行Post请求,参数格式JSON形式
         */
    
        public static String postJsonByHttpClient(String url) {
            //创建HttpClient实例
            try(CloseableHttpClient client = HttpClients.createDefault()){
                //创建HttpPost请求
                HttpPost httpPost = new HttpPost(url);
    
                //设置鉴权参数
                String token = "";
                httpPost.setHeader("Authorization", token);
    
                //设置请求参数
                RequestParam param = new RequestParam();
                param.setName("张三");
                param.setAge(18);
                String json = JSON.toJSONString(param);
                StringEntity entity = new StringEntity(json, "UTF-8");
                httpPost.setEntity(entity);
    
                //设置请求方式(JSON形式)
                httpPost.setHeader("Content-Type", "application/json");
    
                //发送请求并获取响应
                try(CloseableHttpResponse response = client.execute(httpPost)){
                    if(response.getStatusLine().getStatusCode() == 200){
                        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
                        return EntityUtils.toString(response.getEntity(), "UTF-8");
                    }
                }
    
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

    三、OkHttp与HttpClient核心功能对比

    特性 OkHttp HttpClient
    协议支持 HTTP/2、SPDY(自动协商) HTTP/1.1
    连接池 自动复用连接,减少延迟 需手动配置连接池
    GZIP 压缩 透明压缩请求体/响应体 需手动处理
    缓存机制 内置磁盘缓存(可定制) 无内置缓存,需自行实现
    超时控制 统一全局或单请求超时 支持细粒度超时(连接、读取、请求)
    拦截器 支持(修改请求、日志、重试等) 无原生拦截器,需扩展接口
    异步请求 通过 enqueue() 实现 需使用 CloseableHttpAsyncClient
    Cookie 管理 内置 CookieJar 接口 需依赖 CookieStore 实现

    四 、总结

    本文介绍了OKHttp和HttpClient两个客户端的功能、适用场景等。同时,通过实际的示例代码,演示了如何发送GET和POST请求和处理响应内容。大家可以根据自己的项目需求,选择合适的HTTP客户端库实现高效、安全的通信。 有待改正的地方,欢迎各位朋友留言评论。

    你可能感兴趣的:(http,okhttp,网络协议,java,spring,boot)