forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
81 lines (60 loc) · 2.5 KB
/
Main.java
File metadata and controls
81 lines (60 loc) · 2.5 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
77
78
79
80
81
package modern.challenge;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("Accept-Encoding", "gzip")
.uri(URI.create("https://davidwalsh.name"))
.build();
HttpResponse<InputStream> response = client.send(
request, HttpResponse.BodyHandlers.ofInputStream());
System.out.println("Status code: " + response.statusCode());
String encoding = response.headers().firstValue("Content-Encoding").orElse("");
System.out.println("\nEncoding: " + encoding + "\n");
if ("gzip".equals(encoding)) {
String gzipAsString = gzipToString(response.body());
System.out.println(gzipAsString);
} else {
String isAsString = isToString(response.body());
System.out.println(isAsString);
}
}
public static String gzipToString(InputStream gzip) throws IOException {
byte[] allBytes;
try ( InputStream fromIs = new GZIPInputStream(gzip)) {
allBytes = fromIs.readAllBytes();
}
return new String(allBytes, StandardCharsets.UTF_8);
}
public static String isToString(InputStream is) throws IOException {
byte[] allBytes;
try ( InputStream fromIs = is) {
allBytes = fromIs.readAllBytes();
}
return new String(allBytes, StandardCharsets.UTF_8);
}
// or
/*
public static String gzipToString(InputStream gzip) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try ( InputStream fromIs = new GZIPInputStream(gzip); ByteArrayOutputStream toOs = os) {
fromIs.transferTo(toOs);
}
return new String(os.toByteArray(), StandardCharsets.UTF_8);
}
public static String isToString(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try ( InputStream fromIs = is; ByteArrayOutputStream toOs = os) {
fromIs.transferTo(toOs);
}
return new String(os.toByteArray(), StandardCharsets.UTF_8);
}*/
}