/
HttpRequest.java
211 lines (173 loc) · 7.24 KB
/
HttpRequest.java
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
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.util.io;
import com.google.gson.JsonParseException;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.util.Pair;
import org.jackhuang.hmcl.util.function.ExceptionalBiConsumer;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.jackhuang.hmcl.util.Lang.mapOf;
import static org.jackhuang.hmcl.util.Lang.wrap;
import static org.jackhuang.hmcl.util.gson.JsonUtils.GSON;
import static org.jackhuang.hmcl.util.io.NetworkUtils.createHttpConnection;
import static org.jackhuang.hmcl.util.io.NetworkUtils.resolveConnection;
public abstract class HttpRequest {
protected final String url;
protected final String method;
protected final Map<String, String> headers = new HashMap<>();
protected ExceptionalBiConsumer<URL, Integer, IOException> responseCodeTester;
protected final Set<Integer> toleratedHttpCodes = new HashSet<>();
protected boolean ignoreHttpCode;
private HttpRequest(String url, String method) {
this.url = url;
this.method = method;
}
public HttpRequest accept(String contentType) {
return header("Accept", contentType);
}
public HttpRequest authorization(String token) {
return header("Authorization", token);
}
public HttpRequest authorization(String tokenType, String tokenString) {
return authorization(tokenType + " " + tokenString);
}
public HttpRequest authorization(Authorization authorization) {
return authorization(authorization.getTokenType(), authorization.getAccessToken());
}
public HttpRequest header(String key, String value) {
headers.put(key, value);
return this;
}
public HttpRequest ignoreHttpCode() {
ignoreHttpCode = true;
return this;
}
public abstract String getString() throws IOException;
public CompletableFuture<String> getStringAsync() {
return CompletableFuture.supplyAsync(wrap(this::getString), Schedulers.io());
}
public <T> T getJson(Class<T> typeOfT) throws IOException, JsonParseException {
return JsonUtils.fromNonNullJson(getString(), typeOfT);
}
public <T> T getJson(Type type) throws IOException, JsonParseException {
return JsonUtils.fromNonNullJson(getString(), type);
}
public <T> CompletableFuture<T> getJsonAsync(Class<T> typeOfT) {
return getStringAsync().thenApplyAsync(jsonString -> JsonUtils.fromNonNullJson(jsonString, typeOfT));
}
public <T> CompletableFuture<T> getJsonAsync(Type type) {
return getStringAsync().thenApplyAsync(jsonString -> JsonUtils.fromNonNullJson(jsonString, type));
}
public HttpRequest filter(ExceptionalBiConsumer<URL, Integer, IOException> responseCodeTester) {
this.responseCodeTester = responseCodeTester;
return this;
}
public HttpRequest ignoreHttpErrorCode(int code) {
toleratedHttpCodes.add(code);
return this;
}
public HttpURLConnection createConnection() throws IOException {
HttpURLConnection con = createHttpConnection(new URL(url));
con.setRequestMethod(method);
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
return con;
}
public static class HttpGetRequest extends HttpRequest {
public HttpGetRequest(String url) {
super(url, "GET");
}
public String getString() throws IOException {
HttpURLConnection con = createConnection();
con = resolveConnection(con);
return IOUtils.readFullyAsString(con.getInputStream(), StandardCharsets.UTF_8);
}
}
public static final class HttpPostRequest extends HttpRequest {
private byte[] bytes;
public HttpPostRequest(String url) {
super(url, "POST");
}
public HttpPostRequest contentType(String contentType) {
headers.put("Content-Type", contentType);
return this;
}
public HttpPostRequest json(Object payload) throws JsonParseException {
return string(payload instanceof String ? (String) payload : GSON.toJson(payload), "application/json");
}
public HttpPostRequest form(Map<String, String> params) {
return string(NetworkUtils.withQuery("", params), "application/x-www-form-urlencoded");
}
@SafeVarargs
public final HttpPostRequest form(Pair<String, String>... params) {
return form(mapOf(params));
}
public HttpPostRequest string(String payload, String contentType) {
bytes = payload.getBytes(UTF_8);
header("Content-Length", "" + bytes.length);
contentType(contentType + "; charset=utf-8");
return this;
}
public String getString() throws IOException {
HttpURLConnection con = createConnection();
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
os.write(bytes);
}
if (responseCodeTester != null) {
responseCodeTester.accept(new URL(url), con.getResponseCode());
} else {
if (con.getResponseCode() / 100 != 2) {
if (!ignoreHttpCode && !toleratedHttpCodes.contains(con.getResponseCode())) {
String data = NetworkUtils.readData(con);
throw new ResponseCodeException(new URL(url), con.getResponseCode(), data);
}
}
}
return NetworkUtils.readData(con);
}
}
public static HttpGetRequest GET(String url) {
return new HttpGetRequest(url);
}
@SafeVarargs
public static HttpGetRequest GET(String url, Pair<String, String>... query) {
return GET(NetworkUtils.withQuery(url, mapOf(query)));
}
public static HttpPostRequest POST(String url) throws MalformedURLException {
return new HttpPostRequest(url);
}
public interface Authorization {
String getTokenType();
String getAccessToken();
}
}