官方文档地址:http://hc.apache.org/httpcomponents-client-ga/quickstart.html
编辑工具:intelij idea
httpclient是自动化工程的第一步,两个步骤带你快速开始httpclient
1. 准备http请求
2. httpclient访问http请求
准备http请求
1.为了快速开始,选择基于本地准备http请求,方法选择创建spring boot项目(不用部署运行环境),在下准备的是sofa boot,差不多
2. 运行spring boot项目,运行成功后,访问地址:http://localhost:8082/json,如果能够访问成功,那就OK了
访问http请求
参照官方文档:http://hc.apache.org/httpcomponents-client-ga/quickstart.html
使用方法:
1. 创建HttpClient对象
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse
稍作改变,代码如下
public class httpClient {
CloseableHttpClient httpclient = HttpClients.createDefault();
@Test
public void test() throws IOException {
//String uri = "http://"+host+url;
HttpGet httpGet = new HttpGet("http://localhost:8082/json2");
CloseableHttpResponse response1 = execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
} finally {
response1.close();
}
}
public CloseableHttpResponse execute(HttpUriRequest httpRequest) throws IOException {
return httpclient.execute(httpRequest);
}
}
返回结果
快速开始远远不够,对于项目需要继续封装