一、使用HttpClient工具来发送Http请求

1.简介

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

HttpClient 相比传统 JDK 自带的 URLConnection,增加了易用性和灵活性,它不仅是客户端发送 HTTP 请求变得容易,而且也方便了开发人员测试接口(基于 HTTP 协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握 HttpClient 是很重要的必修内容,掌握 HttpClient 后,相信对于 HTTP 协议的了解会更加深入。

 

2.应用场景

 

3.HttpClient工具的使用

1)添加依赖

<!-- Apache Http Begin -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>fluent-hc</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.5</version>
</dependency>
<!-- Apache Http End -->

 

 

2)编写测试代码

  @Test
    public void testHttpClient() throws IOException {

        //1.获得HttpClient对象
       
CloseableHttpClient client = HttpClients.createDefault();
        //2.创建请求对象,如果是post请求  HttpPost  如果是get请求  HttpGet对象
       
String uri = "http://www.baidu.com";
        HttpGet get = new HttpGet(uri);
        //3.执行get请求,获得响应消息对象
       
CloseableHttpResponse response = client.execute(get);
        //4.获取响应行
       
StatusLine statusLine = response.getStatusLine();
        //5.获取状态码
       
int code = statusLine.getStatusCode();
        if(code==200){
            //响应成功
           
HttpEntity entity = response.getEntity();
            //6.获取响应体中的内容
//            InputStream is = entity.getContent();
//            byte[] b = new byte[8192];
//            int len = 0;
//            while((len = is.read(b))!=-1){
//                System.out.println(new String(b,0,len));
//            }
//            is.close();
           
System.out.println(EntityUtils.toString(entity, "utf-8"));
        }


    }

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐