大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具有访问HTTP协议基本功能的高效工具类,为后续开发使用提供方便。
文章要点:
- HttpClient使用流程
- 工具类封装
- 使用实例
HttpClient使用流程
1、导入Maven依赖
1 | <dependency> |
2、创建HttpClient实例
1 | HttpClient client = HttpClientBuilder.create().build(); |
3、创建请求方法的实例
GET请求使用HttpGet,POST请求使用HttpPost,并传入请求的URL1
2
3
4// POST请求
HttpPost post = new HttpPost(url);
// GET请求,URL中带请求参数
HttpGet get = new HttpGet(url);
4、添加请求参数
普通形式
1 | List<NameValuePair> list = new ArrayList<>(); |
JSON形式
1 | Map<String,String> map = new HashMap<>(); |
5、发送请求
调用HttpClient实例的execute方法发送请求,返回一个HttpResponse对象
1 | HttpResponse response = client.execute(post); |
6、获取结果
1 | String result = EntityUtils.toString(response.getEntity()); |
7、释放连接
1 | post.releaseConnection(); |
工具类封装
HttpClient工具类代码(根据相应使用场景进行封装):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63public class HttpClientUtil {
// 发送GET请求
public static String getRequest(String path, List<NameValuePair> parametersBody) throws RestApiException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(path);
uriBuilder.setParameters(parametersBody);
HttpGet get = new HttpGet(uriBuilder.build());
HttpClient client = HttpClientBuilder.create().build();
try {
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code >= 400)
throw new RuntimeException((new StringBuilder()).append("Could not access protected resource. Server returned http code: ").append(code).toString());
return EntityUtils.toString(response.getEntity());
}
catch (ClientProtocolException e) {
throw new RestApiException("postRequest -- Client protocol exception!", e);
}
catch (IOException e) {
throw new RestApiException("postRequest -- IO error!", e);
}
finally {
get.releaseConnection();
}
}
// 发送POST请求(普通表单形式)
public static String postForm(String path, List<NameValuePair> parametersBody) throws RestApiException {
HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8);
return postRequest(path, "application/x-www-form-urlencoded", entity);
}
// 发送POST请求(JSON形式)
public static String postJSON(String path, String json) throws RestApiException {
StringEntity entity = new StringEntity(json, Charsets.UTF_8);
return postRequest(path, "application/json", entity);
}
// 发送POST请求
public static String postRequest(String path, String mediaType, HttpEntity entity) throws RestApiException {
logger.debug("[postRequest] resourceUrl: {}", path);
HttpPost post = new HttpPost(path);
post.addHeader("Content-Type", mediaType);
post.addHeader("Accept", "application/json");
post.setEntity(entity);
try {
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code >= 400)
throw new RestApiException(EntityUtils.toString(response.getEntity()));
return EntityUtils.toString(response.getEntity());
}
catch (ClientProtocolException e) {
throw new RestApiException("postRequest -- Client protocol exception!", e);
}
catch (IOException e) {
throw new RestApiException("postRequest -- IO error!", e);
}
finally {
post.releaseConnection();
}
}
}
使用实例
GET请求
1 | List<NameValuePair> parametersBody = new ArrayList(); |
POST请求
1 | List<NameValuePair> parametersBody = new ArrayList(); |
POST请求(JSON形式)
1 | Map<String,String> map = new HashMap<>(); |
关于HttpClient的详细介绍看这里:HttpClient入门
本文为作者kMacro原创,转载请注明来源:https://zkhdev.github.io/2018/10/12/java-dev5/