
HttpClient调用外部项目接口工具类示例
5星
- 浏览量: 0
- 大小:None
- 文件类型:PDF
简介:
本工具类提供通过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
全部评论 (0)


