简单http工具
Salted Fish 2025/10/28 Utils
# 工具类
import cn.hutool.core.net.DefaultTrustManager;
import com.alibaba.fastjson2.JSON;
import com.salted.fish.utils.encryption.EncryptUtil;
import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.List;
import java.util.Map;
/**
* @description:简单http工具
* @author:saltedFish
* @create:2021-03-30
* @Version:
*/
public class EasyHttp {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final int OK = 200;
private static final int FOUND = 302;
private static SSLSocketFactory sslSocketFactory;
static class Method {
public static final String GET = "GET";
public static final String POST = "POST";
}
static class ContentType {
public static final String JSON = "application/json";
public static final String FORM_URLENCODED = "application/x-www-form-urlencoded";
}
static {
DefaultTrustManager trustManager = new DefaultTrustManager();
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[0], new TrustManager[]{trustManager}, new SecureRandom());
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 建立连接
*
* @param url
* @return
* @throws IOException
*/
private static HttpURLConnection openConnection(String url) throws IOException {
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
if (url.startsWith("https://")) {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
httpsURLConnection.setHostnameVerifier((s, sslSession) -> true);
httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}
//30s
httpURLConnection.setConnectTimeout(30000);
//30s
httpURLConnection.setReadTimeout(30000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
return httpURLConnection;
}
/**
* 设置请求属性
*
* @param httpURLConnection
* @param request
*/
private static void setRequestProperties(HttpURLConnection httpURLConnection, HttpRequest request) {
httpURLConnection.setRequestProperty("Accept", "*/*");
httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome");
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("Host", request.getHost());
if (request.getHeaders() != null) {
request.getHeaders().forEach((k, v) -> {
if (v != null)
httpURLConnection.setRequestProperty(k, v);
});
}
}
/**
* 设置请求数据
*
* @param httpURLConnection
* @param data
* @throws IOException
*/
private static void setRequestData(HttpURLConnection httpURLConnection, Object data) throws IOException {
if (data == null)
return;
byte[] bytes;
if (data instanceof byte[]) {
bytes = (byte[]) data;
} else if (data instanceof String) {
bytes = data.toString().getBytes(UTF8);
} else {
bytes = JSON.toJSONBytes(data);
}
httpURLConnection.getOutputStream().write(bytes);
}
/**
* 执行http方法
*
* @param httpURLConnection
* @return
* @throws IOException
*/
private static HttpResponse execute(HttpURLConnection httpURLConnection) throws IOException {
httpURLConnection.connect();
int code = httpURLConnection.getResponseCode();
String message = httpURLConnection.getResponseMessage();
Map<String, List<String>> headers = httpURLConnection.getHeaderFields();
InputStream in;
if (code == OK || code == FOUND) {
in = httpURLConnection.getInputStream();
} else {
in = httpURLConnection.getErrorStream();
}
byte[] content = null;
if (in != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len;
while ((len = in.read(buff)) != -1) {
baos.write(buff, 0, len);
}
content = baos.toByteArray();
}
return new HttpResponse(code, message, content, headers);
}
/**
* 执行http方法
*
* @param request 请求
* @param keepConnected 保持连接
* @return
* @throws IOException
*/
public static HttpResponse execute(HttpRequest request, boolean keepConnected) throws RuntimeException {
HttpURLConnection httpURLConnection = null;
HttpResponse response = null;
try {
httpURLConnection = openConnection(request.getUrl());
httpURLConnection.setRequestMethod(request.getMethod());
httpURLConnection.setInstanceFollowRedirects(request.isFollowRedirects());
setRequestProperties(httpURLConnection, request);
setRequestData(httpURLConnection, request.getData());
response = execute(httpURLConnection);
} catch (IOException e) {
// 抛出运行时异常
throw new RuntimeException(e);
}
if (!keepConnected) {
httpURLConnection.disconnect();
}
return response;
}
public static HttpResponse get(HttpRequest request) throws RuntimeException {
request.setMethod(Method.GET);
return execute(request, true);
}
public static HttpResponse get(String url) throws RuntimeException {
return get(HttpRequest.builder().url(url).build());
}
public static HttpResponse post(HttpRequest request) throws RuntimeException {
request.setMethod(Method.POST);
return execute(request, true);
}
public static HttpResponse postForm(String url, Headers headers, Object formObject) throws RuntimeException {
StringBuilder sb = new StringBuilder();
if (formObject != null) {
Map<?, ?> form;
if (formObject instanceof Map) {
form = (Map) formObject;
} else {
form = (Map) JSON.toJSON(formObject);
}
form.forEach((key, value) -> {
if (sb.length() > 0)
sb.append('&');
sb.append(key).append('=').append(value == null ? "" : value);
});
}
String data = EncryptUtil.encodeURL(sb.toString());
if (headers == null) {
headers = Headers.create();
}
headers.setContentType(ContentType.FORM_URLENCODED);
return execute(new HttpRequest(Method.POST, url, headers, data), true);
}
public static HttpResponse postJson(String url, Headers headers, Object jsonObject) throws RuntimeException {
if (headers == null) {
headers = Headers.create();
}
headers.setContentType(ContentType.JSON);
return execute(new HttpRequest(Method.POST, url, headers, jsonObject), true);
}
}
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# 请求头对象
import java.util.HashMap;
/**
* @description:请求头对象
* @author:saltedFish
* @create:2021-03-30
* @Version:
*/
public class Headers extends HashMap<String, String> {
public static Headers create() {
return new Headers();
}
public Headers addHeader(String name, String value) {
put(name, value);
return this;
}
public Headers setContentType(String contentType) {
return addHeader("Content-Type", contentType);
}
public Headers setAuthorization(String authorization) {
return addHeader("Authorization", authorization);
}
}
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
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
# 请求对象
import java.net.MalformedURLException;
import java.net.URL;
/**
* @description:请求对象
* @author:saltedFish
* @create:2021-03-30
* @Version:
*/
public class HttpRequest {
private String method;
private String url;
private Headers headers;
private Object data;
private boolean followRedirects;
public HttpRequest() {
}
public HttpRequest(String method, String url, Headers headers, Object data) {
this.method = method;
this.url = url;
this.headers = headers;
this.data = data;
this.followRedirects = true;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Headers getHeaders() {
return headers;
}
public void setHeaders(Headers headers) {
this.headers = headers;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public boolean isFollowRedirects() {
return followRedirects;
}
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
}
public String getHost() {
try {
if (url == null) return null;
return new URL(url).getHost();
} catch (MalformedURLException e) {
return null;
}
}
@Override
public String toString() {
return "HttpRequest{" +
"method='" + method + '\'' +
", url='" + url + '\'' +
", headers=" + headers +
", data=" + data +
", followRedirects=" + followRedirects +
'}';
}
public static class Builder {
private HttpRequest request = new HttpRequest();
public Builder method(String method) {
request.method = method;
return this;
}
public Builder url(String url) {
request.url = url;
return this;
}
public Builder header(String name, String value) {
if (request.headers == null) {
request.headers = new Headers();
}
request.headers.addHeader(name, value);
return this;
}
public Builder headers(Headers headers) {
request.headers = headers;
return this;
}
public Builder data(Object data) {
request.data = data;
return this;
}
public Builder followRedirects(boolean followRedirects) {
request.followRedirects = followRedirects;
return this;
}
public HttpRequest build() {
return request;
}
}
public static Builder builder() {
return new Builder();
}
}
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
126
127
128
129
130
131
132
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
126
127
128
129
130
131
132
# 返回对象
package com.salted.fish.utils.http;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description:返回对象
* @author:saltedFish
* @create:2021-03-30
* @Version:
*/
public class HttpResponse {
private static final int OK = 200;
private int code;
private String message;
private byte[] body;
private int bodyLength;
private Map<String, List<String>> headers;
private List<String> cookies;
public HttpResponse(int code, String message, byte[] body, Map<String, List<String>> headers) {
this.code = code;
this.message = message;
this.body = body;
if (body != null) {
this.bodyLength = body.length;
}
parseHeaders(headers);
}
private void parseHeaders(Map<String, List<String>> headers) {
this.headers = new HashMap<>(headers);
List<String> protocol = this.headers.remove(null);
if (protocol != null) {
this.headers.put("Http-Protocol", protocol);
}
this.cookies = headers.get("Set-Cookie");
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public int getBodyLength() {
return bodyLength;
}
public byte[] getBody() {
return body;
}
public String getBodyAsString() {
if (body == null) {
return null;
}
return new String(body, StandardCharsets.UTF_8);
}
public Map<String, List<String>> getHeaders() {
return new HashMap<>(headers);
}
public List<String> getCookies() {
if (cookies == null) {
return null;
}
return new ArrayList<>(cookies);
}
public boolean isOK() {
return code == OK;
}
}
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
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