This repository was archived by the owner on Oct 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRequest.java
More file actions
76 lines (61 loc) · 2.92 KB
/
HttpRequest.java
File metadata and controls
76 lines (61 loc) · 2.92 KB
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
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
public class HttpRequest {
private static final String USER_AGENT = "Java Application";
public static CompletableFuture<HttpResponse> getData(String urlString, HttpHeader... headers) {
return getData(urlString, "GET", null, headers);
}
public static CompletableFuture<HttpResponse> getData(String urlString, String body, HttpHeader... headers) {
return getData(urlString, "POST", body, headers);
}
public static CompletableFuture<HttpResponse> getData(String urlString, String method, String body, HttpHeader... headers) {
CompletableFuture<HttpResponse> future = new CompletableFuture<>();
Thread t = new Thread(() -> download(future, urlString, method, body, headers), "download_url");
t.start();
return future;
}
private static void download(CompletableFuture<HttpResponse> future, String urlString, String method, String body, HttpHeader... headers) {
try {
BufferedReader br;
String line;
StringBuilder text = new StringBuilder();
HttpsURLConnection connection = (HttpsURLConnection) (new URL(urlString)).openConnection();
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setRequestMethod(method);
connection.setRequestProperty("User-Agent", USER_AGENT);
for (HttpHeader property : headers) {
connection.setRequestProperty(property.getKey(), property.getValue());
}
boolean hasBody = body != null && body.length() > 0;
connection.setDoOutput(hasBody);
if (hasBody) {
byte[] out = body.getBytes(StandardCharsets.UTF_8);
int length = out.length;
connection.setFixedLengthStreamingMode(length);
connection.connect();
try (OutputStream os = connection.getOutputStream()) {
os.write(out);
}
} else connection.connect();
int code = connection.getResponseCode();
if (code / 100 != 2) {
future.complete(new HttpResponse(code));
return;
}
InputStream in = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
while ((line = br.readLine()) != null) {
text.append(line).append("\n");
}
br.close();
in.close();
future.complete(new HttpResponse(text.toString(), connection.getHeaderFields(), code));
} catch (Throwable e) {
future.completeExceptionally(e);
}
}
}