本工具类提供通过HttpClient访问外部系统API的功能示例,包括GET和POST请求方法,适用于Java项目的集成开发。
HttpClient是Apache Jakarta Commons子项目中的一个开源Http客户端实现工具库,支持HTTP1.1和2.0协议,并提供发送请求及接收响应的功能。
使用HttpClient的优点包括简化了Http请求的处理流程、提供了更好的性能与可靠性。它也支持HTTPS加密连接以及Cookies、Session和Authentication等功能。
下面是一个示例代码展示如何利用HttpClient来实现调用外部项目接口工具类:
首先,需要引入相关的依赖项:
```java
import org.apache.http.NameValuePair;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
```
然后,可以创建一个名为HttpUtils的工具类来发送HttpGet和HttpPost请求:
```java
public class HttpUtils {
private static RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.build();
public static String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
entity = response.getEntity();
if (entity != null) {
responseContent = EntityUtils.toString(entity, UTF-8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
if (httpClient != null)
httpClient.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return responseContent;
}
public static String sendHttpPost(String httpUrl, Map maps) {
HttpPost httpPost = new HttpPost(httpUrl);
List params = new ArrayList<>();
for (Map.Entry entry : maps.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, UTF-8);
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String responseContent = EntityUtils.toString(responseEntity, UTF-8);
return responseContent;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
在上述示例中,我们创建了一个名为HttpUtils的工具类,并提供了两个方法:`sendHttpGet()` 和 `sendHttpPost()`。前者用于发送GET请求,后者用于提交POST数据。
使用HttpClient时需要注意以下几点:
- 正确配置超时时间等参数;
- 确保关闭连接以释放资源;
- 适当处理可能出现的各种异常情况。
通过合理运用和设置这些特性,可以确保HttpClient的高效与稳定。