发送 HTTP 请求
在开发中,有时候会遇到需要调用现成的接口,我们就可以使用 Apache 提供的 Java 工具类 HttpClient。
一、引入 Maven 坐标
使用 Apache 的 HttpClient 需要引入相关的 Maven 坐标,Maven 坐标如下:
<!-- HttpClient 相关依赖-->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient-cache -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
</dependency>
二、发送 GET 请求
不携带参数的 GET 请求的方法如下:
/**
* 功能描述: 使用 get 请求直接访问 url,不带参数
*
* @param url
* @return: java.lang.String
* @author: 路人WL
* @date: 2020/4/27
*/
public static String doGet(String url) throws Exception {
// 创建 HttpClient 对象
CloseableHttpClient client = HttpClients.createDefault();
// 创建访问地址
URIBuilder uriBuilder = new URIBuilder(url);
// 创建 http 对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 执行 get 请求
CloseableHttpResponse httpResponse = client.execute(httpGet);
// 接收回复的内容
String result = null;
if (httpResponse.getStatusLine