HttpClient的使用步骤:
- 创建一个Http客户端(可以进行个性化配置)
- 创建请求(常见的get、post请求)
- 客户端发送请求,获取响应内容,解析响应内容
一、创建Http客户端
/** * 第一种方式 * 静态方法, 创建HTTP客户端, 返回 CloseableHttpClient 实例 * 本质上使用 HttpClientBuilder.create().build() 创建的(即下面要介绍到的第二种方法) */ CloseableHttpClient httpClient = HttpClients.createDefault();
/** * 第二种方式:灵活可配置 */ //调用的是 HttpClientBuilder.create(); HttpClientBuilder httpClientBuilder = HttpClients.custom(); /** * 使用 HttpClientBuilder 可以进行个性化配置,后面单独地详细说 */ //创建http客户端 CloseableHttpClient httpClient = httpClientBuilder.build();
二、创建请求
/** * 第一种方式 * HttpGet和 HttpPost都实现了 HttpUriRequest接口, 本质上与第二种方式效果是一致的 * 可以调用实例方法进行个性化设置,这个后面再详细地讲解 */ HttpGet httpGet = new HttpGet("https://www.baidu.com/"); HttpPost httpPost = new HttpPost("https://www.baidu.com/");
/** * 第二种方式 * 借助 RequestBuilder 完成 */ RequestBuilder requestBuilder = RequestBuilder.get().setUri("https://www.baidu.com/"); /** * RequestBuilder的实例方法可以对请求进行个性化配置,效果等同于第一种方式的HttpGet或HttpPost的实例方法 */ HttpUriRequest httpGet = requestBuilder.build();
三、解析响应内容
//创建 http 客户端 HttpClientBuilder httpClientBuilder = HttpClients.custom(); CloseableHttpClient httpClient = httpClientBuilder.build(); //创建 请求 RequestBuilder requestBuilder = RequestBuilder.get().setUri("https://www.baidu.com/"); HttpUriRequest httpGet = requestBuilder.build(); //获取响应对象 CloseableHttpResponse response = null; try { response = httpClient.execute(httpGet); //获取响应状态行,进而获取响应状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("状态码:" + statusCode); //获取响应的MIME类型 String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType(); System.out.println("媒体类型:" + contentMimeType); //获取响应的内容,这里只演示简单的文本内容,实际开发中并不总是这么简单,后面详细地讲解 String bodyAsString = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println("响应内容:" + bodyAsString); } catch (IOException e) { e.printStackTrace(); }finally { //关闭响应 if(null != response){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } //释放连接 if(null != httpGet){ httpGet.abort(); } //关闭客户端 if(null != httpClient){ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } }
注:这里要记得关闭相关的资源