Http请求工具类


www.srblog.cn

前言

在项目开发中,经常需要请求第三方接口,这里参考网络资料,特此封装了一个工具类,中间穿插使用了java8的一些新特性:Lambda 表达式、Optional类等,不足之处还请指出


代码

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
public class HttpUtils {

public final static Gson gson = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();

public static String postByForm(String serverUrl, Map<String, Object> data) {
BufferedWriter writer = null;
String result = null;
HttpURLConnection connection = null;
try {
URL url = new URL(serverUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
//设置表单类型
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//根据接口要求,设置编码类型
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
connection.connect();
if (data != null && !data.isEmpty()) {
StringBuilder urlParams = new StringBuilder();
//拼接参数
data.forEach((s, o) -> urlParams.append(s).append("=").append(o).append("&"));
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
writer.write(urlParams.substring(0, urlParams.length() - 1));
//写入数据结束后,及时关闭流操作,切记
writer.close();
connection.getOutputStream().flush();
}
String contentEncoding = connection.getContentEncoding();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
if (contentEncoding.equals("gzip")) {
inputStream = new GZIPInputStream(inputStream);
} else if (contentEncoding.equals("deflate")) {
inputStream = new DeflaterInputStream(inputStream);
}
//解析服务器响应结果
result = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining(System.lineSeparator()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {

if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}

}
return result;
}

public static String postByJson(String serverUrl, Object data) {
BufferedWriter writer = null;
String result = null;
HttpURLConnection connection = null;
try {
URL url = new URL(serverUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(5 * 1000);
connection.setConnectTimeout(5 * 1000);
connection.setUseCaches(false);
//设置json类型
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//设置编码格式
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
connection.connect();
//如果data不为空,则isPresent()返回true,反之为false
if (Optional.ofNullable(data).isPresent()) {
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
//直接写入转化后的Json字符串
writer.write(gson.toJson(data));
//写入数据结束后,及时关闭流操作,切记
writer.close();
connection.getOutputStream().flush();
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String contentEncoding = connection.getContentEncoding();
//根据编码格式解压缩
if (contentEncoding.equals("gzip")) {
inputStream = new GZIPInputStream(inputStream);
} else if (contentEncoding.equals("deflate")) {
inputStream = new DeflaterInputStream(inputStream);
}
//解析服务器响应结果
result = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining(System.lineSeparator()));
}

} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}

}

使用

根据请求类型,直接调用工具类,选择封装Map或Object对象即可(根据接口要求,自行更改相应配置参数)。

sr wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
0%