一、 导入jar包
<!--添加httpClient jar包 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
二、 HttpClient入门案例
/**
* 1.测试HttpClient中的get请求
* 步骤:
* 1.实例化httpClient对象
* 2.确定访问url地址
* 3.封装请求的类型get/post/put/delete
* 4.发起http请求,获取响应对象response.
* 5.校验返回对象的状态码信息.
* 200表示成功
* 400请求的参数异常
* 404请求路径不匹配
* 406请求的返回值类型异常
* 500后台服务器运行异常
* 504请求超时.后台服务器宕机/遇忙
* 6.如果状态码信息为200,则动态的获取响应数据.
* 7.获取返回值数据,之后进行业务调用.
*/
@Test
public void testGet() throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
String url = "https://www.baidu.com";
HttpGet httpGet = new HttpGet(url);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
//表示用户请求成功!!
HttpEntity entity = httpResponse.getEntity();//返回值数据的实体对象
String json = EntityUtils.toString(entity, "utf-8");
System.out.println(json);
} else {
//一定请求有误.
System.out.println("服务器正忙,请稍后!!!");
}
}
@Test
public void testGet() throws ClientProtocolException, IOException {
//定义httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
String uri = "https://item.jd.com/5236335.html?dist=jd";
HttpGet httpGet = new HttpGet(uri);
//获取请求的全部参数 GET https://item.jd.com/5236335.html?dist=jd HTTP/1.1
RequestLine requestLine = httpGet.getRequestLine();
//获取请求方式 GET/POST
requestLine.getMethod();
//获取浏览器 http协议 HTTP/1.1
requestLine.getProtocolVersion();
//请求 uri:https://item.jd.com/5236335.html?dist=jd
requestLine.getUri();
//获取HTTP响应
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
System.out.println("获取请成功");
//获取HTML
String html = EntityUtils.toString(httpResponse.getEntity());
System.out.println(html);
}
}