前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HttpClient 基础知识

HttpClient 基础知识

作者头像
Remember_Ray
发布2020-09-15 10:09:18
5700
发布2020-09-15 10:09:18
举报
文章被收录于专栏:Ray学习笔记

HttpClient

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接

依赖

代码语言:javascript
复制
<!-- HttpClient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

GET请求

代码语言:javascript
复制
public class HttpGetTest {

    public static void main(String[] args) {
        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpGet 对象,需要设置 url 访问地址
        //String url = "http://www.itcast.cn";
        String url = "https://www.baidu.cn";
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = null;
        try {
            // 使用 HttpClient 发起请求,获取 response 响应
            response = httpClient.execute(httpGet);

            // 解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                //System.out.println(content);
                System.out.println(content.length());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭 response
                response.close();
                // 关闭 httpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

带参数的GET请求

代码语言:javascript
复制
public class HttpGetParamTest {

    public static void main(String[] args) throws URISyntaxException {
        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 设置请求地址:http://yun.itheima.com/tiyan/java?bz=spk
        String url = "http://yun.itheima.com/tiyan/java";

        // 创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);
        // 设置参数
        uriBuilder.setParameter("bz", "spk");
        //uriBuilder.setParameter("bz", "spk").setParameter("", "");

        // 创建 HttpGet 对象,需要设置 url 访问地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        //发起请求的信息: GET http://www.itcast.cn HTTP/1.1
        System.out.println("发起请求的信息: " + httpGet);

        CloseableHttpResponse response = null;
        try {
            // 使用 HttpClient 发起请求,获取 response 响应
            response = httpClient.execute(httpGet);

            // 解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                //System.out.println(content);
                System.out.println(content.length());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭 response
                response.close();
                // 关闭 httpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

POST请求

代码语言:javascript
复制
public class HttpPostTest {

    public static void main(String[] args) {
        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 对象,需要设置 url 访问地址
        String url = "http://www.itcast.cn";
        HttpPost httpPost = new HttpPost(url);

        CloseableHttpResponse response = null;
        try {
            // 使用 HttpClient 发起请求,获取 response 响应
            response = httpClient.execute(httpPost);

            // 解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                //System.out.println(content);
                System.out.println(content.length());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭 response
                response.close();
                // 关闭 httpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

带参数的POST请求

代码语言:javascript
复制
public class HttpPostParamTest {

    public static void main(String[] args) throws UnsupportedEncodingException {
        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 对象,需要设置 url 访问地址
        String url = "http://yun.itheima.com/search";
        HttpPost httpPost = new HttpPost(url);

        // 声明 List 集合,封装表单中的请求参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("keys", "Java"));

        // 创建表单的Entity对象,第一个参数是封装好的表单数据,第二个参数是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf8");

        // 设置表单的Entity对象到Post请求中
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            // 使用 HttpClient 发起请求,获取 response 响应
            response = httpClient.execute(httpPost);

            // 解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                //System.out.println(content);
                System.out.println(content.length());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭 response
                response.close();
                // 关闭 httpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

连接池

如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。

测试以下代码,并断点查看每次获取的HttpClient都是不一样的。

代码语言:javascript
复制
public class HttpClientPoolTest {

    public static void main(String[] args) {

        // 创建连接池管理器
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();

        // 设置最大连接数
        manager.setMaxTotal(100);

        // 设置每个主机的最大连接数,防止HOST不均衡
        manager.setDefaultMaxPerRoute(10);

        // 使用连接池管理器发起请求
        doGet(manager);
        doGet(manager);

    }

    private static void doGet(PoolingHttpClientConnectionManager manager) {
        // 不是每次创建新的 HttpClient,而是从连接池中获取 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(manager).build();

        // 创建 HttpGet 对象,需要设置 url 访问地址
        String url = "http://www.itcast.cn";
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                    // 不能关闭 HttpClient,由连接池管理了
                    //httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

请求参数

有时候因为网络,或者目标服务器的原因,请求需要更长的时间才能完成,我们需要自定义相关时间

代码语言:javascript
复制
public class HttpConfigTest {

    public static void main(String[] args) {
        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpGet 对象,需要设置 url 访问地址
        String url = "http://www.itcast.cn";
        HttpGet httpGet = new HttpGet(url);


        // 配置请求信息
        RequestConfig config = RequestConfig.custom()
                // 设置创建连接的最长时间,单位毫秒
                .setConnectTimeout(1000)
                // 设置获取连接的最长时间,单位毫秒
                .setConnectionRequestTimeout(500)
                // 设置数据传输的最长时间,单位毫秒
                .setSocketTimeout(10 * 1000)
                .build();

        // 给请求设置请求信息
        httpGet.setConfig(config);


        CloseableHttpResponse response = null;
        try {
            // 使用 HttpClient 发起请求,获取 response 响应
            response = httpClient.execute(httpGet);

            // 解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                //System.out.println(content);
                System.out.println(content.length());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭 response
                response.close();
                // 关闭 httpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-08-07|,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • HttpClient
    • 使用方法
      • 依赖
        • GET请求
          • 带参数的GET请求
            • POST请求
              • 带参数的POST请求
                • 连接池
                  • 请求参数
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档