一、开始使用httpclient
本文档需要使用的依赖有如下几个:
<dependency><groupId>org.apache.httpcomponentsgroupId><artifactId>httpclientartifactId><version>4.5.10version>dependency><dependency><groupId>org.apache.httpcomponentsgroupId><artifactId>httpmimeartifactId><version>4.5.10version>dependency><dependency><groupId>org.apache.httpcomponentsgroupId><artifactId>httpcoreartifactId><version>4.4.11version>dependency>
1、创建HttpClient对象。
创建httpclient对象的方式有两种,
第一种是使用默认配置创建:
CloseableHttpClient client = HttpClients.createDefault();
第二种是使用HttpClients.custom()定制:
HttpClients.custom().setDefaultRequestConfig(RequestConfig);
这其中RequestConfig的设计方式可以学习一下,也即是建造者模式。RequestConfig只有一个默认访问修饰符的构造函,这就意味着我们在使用这个类的时候不能之间构建示例;RequestConfig有很多私有属性,这些属性没有get/set方法,所以,即便是我们拿到了RequestConfig类的实例,也不能去修改其中的属性值。那么RequestConfig是如何构造实例并且为属性赋值的呢?RequestConfig在实例化的时候会利用其公共内部类Builder。使用方式为RequestConfig.custom().setXXX().builder()。调用custom方法返回一个Builder类实例,改类里有设置RequestConfig同名属性的各种方法,设置完毕后调用builder方法构造一个新的RequestConfig实例。从这个过程中可以看出来,RequestConfig对象的属性是不可变的。
有几个参数我们自己必须设置一下:
(1)connectionRequestTimeout&