Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/httpclient/BodyProcessorInputStreamTest.java
41149 views
1
/*
2
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import java.io.InputStream;
25
import java.io.InputStreamReader;
26
import java.io.Reader;
27
import java.net.URI;
28
import java.net.http.HttpClient;
29
import java.net.http.HttpHeaders;
30
import java.net.http.HttpRequest;
31
import java.net.http.HttpResponse;
32
import java.net.http.HttpResponse.BodyHandlers;
33
import java.nio.charset.Charset;
34
import java.util.Locale;
35
import java.util.Optional;
36
import java.util.concurrent.CompletableFuture;
37
import java.util.stream.Stream;
38
import static java.lang.System.err;
39
40
/*
41
* @test
42
* @bug 8187503
43
* @summary An example on how to read a response body with InputStream.
44
* @run main/othervm/manual -Dtest.debug=true BodyProcessorInputStreamTest
45
* @author daniel fuchs
46
*/
47
public class BodyProcessorInputStreamTest {
48
49
public static boolean DEBUG = Boolean.getBoolean("test.debug");
50
51
/**
52
* Examine the response headers to figure out the charset used to
53
* encode the body content.
54
* If the content type is not textual, returns an empty Optional.
55
* Otherwise, returns the body content's charset, defaulting to
56
* ISO-8859-1 if none is explicitly specified.
57
* @param headers The response headers.
58
* @return The charset to use for decoding the response body, if
59
* the response body content is text/...
60
*/
61
public static Optional<Charset> getCharset(HttpHeaders headers) {
62
Optional<String> contentType = headers.firstValue("Content-Type");
63
Optional<Charset> charset = Optional.empty();
64
if (contentType.isPresent()) {
65
final String[] values = contentType.get().split(";");
66
if (values[0].startsWith("text/")) {
67
charset = Optional.of(Stream.of(values)
68
.map(x -> x.toLowerCase(Locale.ROOT))
69
.map(String::trim)
70
.filter(x -> x.startsWith("charset="))
71
.map(x -> x.substring("charset=".length()))
72
.findFirst()
73
.orElse("ISO-8859-1"))
74
.map(Charset::forName);
75
}
76
}
77
return charset;
78
}
79
80
public static void main(String[] args) throws Exception {
81
HttpClient client = HttpClient.newHttpClient();
82
HttpRequest request = HttpRequest
83
.newBuilder(new URI("http://hg.openjdk.java.net/jdk9/sandbox/jdk/shortlog/http-client-branch/"))
84
.GET()
85
.build();
86
87
// This example shows how to return an InputStream that can be used to
88
// start reading the response body before the response is fully received.
89
// In comparison, the snipet below (which uses
90
// HttpResponse.BodyHandlers.ofString()) obviously will not return before the
91
// response body is fully read:
92
//
93
// System.out.println(
94
// client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).get().body());
95
96
CompletableFuture<HttpResponse<InputStream>> handle =
97
client.sendAsync(request, BodyHandlers.ofInputStream());
98
if (DEBUG) err.println("Request sent");
99
100
HttpResponse<InputStream> pending = handle.get();
101
102
// At this point, the response headers have been received, but the
103
// response body may not have arrived yet. This comes from
104
// the implementation of HttpResponseInputStream::getBody above,
105
// which returns an already completed completion stage, without
106
// waiting for any data.
107
// We can therefore access the headers - and the body, which
108
// is our live InputStream, without waiting...
109
HttpHeaders responseHeaders = pending.headers();
110
111
// Get the charset declared in the response headers.
112
// The optional will be empty if the content type is not
113
// of type text/...
114
Optional<Charset> charset = getCharset(responseHeaders);
115
116
try (InputStream is = pending.body();
117
// We assume a textual content type. Construct an InputStream
118
// Reader with the appropriate Charset.
119
// charset.get() will throw NPE if the content is not textual.
120
Reader r = new InputStreamReader(is, charset.get())) {
121
122
char[] buff = new char[32];
123
int off=0, n=0;
124
if (DEBUG) err.println("Start receiving response body");
125
if (DEBUG) err.println("Charset: " + charset.get());
126
127
// Start consuming the InputStream as the data arrives.
128
// Will block until there is something to read...
129
while ((n = r.read(buff, off, buff.length - off)) > 0) {
130
assert (buff.length - off) > 0;
131
assert n <= (buff.length - off);
132
if (n == (buff.length - off)) {
133
System.out.print(buff);
134
off = 0;
135
} else {
136
off += n;
137
}
138
assert off < buff.length;
139
}
140
141
// last call to read may not have filled 'buff' completely.
142
// flush out the remaining characters.
143
assert off >= 0 && off < buff.length;
144
for (int i=0; i < off; i++) {
145
System.out.print(buff[i]);
146
}
147
148
// We're done!
149
System.out.println("Done!");
150
}
151
}
152
153
}
154
155