HttpClient-4.5总结(1)

apache httpclient不多介绍这个工具是什么,具体请看官网,不赘述。

进行记录的原因一个是把掉过坑的地方记住,另一个是自httpclient-4.4开始,官方对代码进行了很多调整,4.4以前的很多class和method都过时了,而国内之前很多关于httpclient的分享都是4.4之前的。

个人感觉使用Httpclient比较重要的是看它的代码,和官方的一些例子,可能是网络知识比较短板的原因,官方的tutorial其实看起来挺不清晰的,感觉主线不明确,不能引导你很好的学习,建议初学的人同时结合官网源码官方例子、tutorial进行学习。

先看第一个demo,把这个东西用起来再说。

/**
 * 使用httpclient-4.5.2发送请求
 * @author chmod400
 * 2016.3.24
 */
public class FirstHttpClientDemo {

    public static void main(String[] args) {
        try {
            String url = "http://www.baidu.com";
            // 使用默认配置创建httpclient的实例
            CloseableHttpClient client = HttpClients.createDefault();
            
            HttpPost post = new HttpPost(url);
//          HttpGet get = new HttpGet(url);
            
            CloseableHttpResponse response = client.execute(post);
//          CloseableHttpResponse response = client.execute(get);
            
            // 服务器返回码
            int status_code = response.getStatusLine().getStatusCode();
            System.out.println("status_code = " + status_code);
            
            // 服务器返回内容
            String respStr = null;
            HttpEntity entity = response.getEntity();
            if(entity != null) {
                respStr = EntityUtils.toString(entity, "UTF-8");
            }
            System.out.println("respStr = " + respStr);
            // 释放资源
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这个demo主要是完成基本的交互过程,发送请求,接收消息,如果只是做小程序或者不是特别大并发量的系统,基本已经够用了。

进行一些说明:

1.需要向服务器发送请求,我们需要一个org.apache.http.client.HttpClient的实例对象,一般使用的都是org.apache.http.impl.client.CloseableHttpClient,创建该对象的最简单方法是CloseableHttpClient client = HttpClients.createDefault();,HttpClients是负责创建CloseableHttpClient的工厂,现在我们用最简单的方法就是使用默认配置去创建实例,后面我们再讨论有参数定制需求的实例创建方法。我们可以通过打断点的方式看到这个默认的实例对象的连接管理器org.apache.http.conn.HttpClientConnectionManager请求配置org.apache.http.client.config.RequestConfig等配置的默认参数,这些都是后面需要了解的。

2.构造请求方法HttpPost post = new HttpPost(url);表示我们希望用那种交互方法与服务器交互,HttpClient为每种交互方法都提供了一个类:HttpGet,
HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, 还有 HttpOptions。

3.向服务器提交请求CloseableHttpResponse response = client.execute(post);,很明显`CloseableHttpResponse就是用了处理返回数据的实体,通过它我们可以拿到返回的状态码、返回实体等等我们需要的东西。

4.EntityUtils是官方提供一个处理返回实体的工具类,toString方法负责将返回实体装换为字符串,官方是不太建议使用这个类的,除非返回数据的服务器绝对可信和返回的内容长度是有限的。官方建议是自己使用HttpEntity#getContent()或者HttpEntity#writeTo(OutputStream),需要提醒的是记得关闭底层资源。

5.EntityUtils.consume(entity);负责释放资源,通过源码可知,是需要把底层的流关闭:

InputStream instream = entity.getContent();
if (instream != null) {
    instream.close();
}

好了,到此已经完成了httpclient的第一个demo。
jar包地址:Apache HttpClient 4.5.2Apache HttpCore 4.4

    原文作者:李不言被占用了
    原文地址: https://www.jianshu.com/p/a44407f48321
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞