下面列出了java.net.http.HttpResponse.BodyHandlers#java.net.http.HttpClient 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void bodyExample() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(
"{\"email\":\"[email protected]\",\"password\":\"cityslicka\"}"))
.uri(URI.create("https://reqres.in/api/login"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println("\n Body: " + response.body());
}
public void authenticatorExample() throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"username",
"password".toCharArray());
}
}).build();
HttpRequest request = HttpRequest.newBuilder()
// ...
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
}
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Version: " + response.version());
System.out.println("\nURI: " + response.uri());
System.out.println("\nStatus code: " + response.statusCode());
System.out.println("\nHeaders: " + response.headers());
System.out.println("\n Body: " + response.body());
}
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://http2.golang.org/serverpush"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler())
.thenApply(HttpResponse::body)
.thenAccept((b) -> System.out.println("\nMain resource:\n" + b))
.join();
System.out.println("\nPush promises map size: " + promisesMap.size() + "\n");
promisesMap.entrySet().forEach((entry) -> {
System.out.println("Request = " + entry.getKey()
+ ", \nResponse = " + entry.getValue().join().body());
});
}
public static void main(String[] args) throws IOException, InterruptedException {
Map<Object, Object> data = new LinkedHashMap<>();
data.put("author", "Lorem Ipsum Generator");
data.put("filefield", Path.of("LoremIpsum.txt"));
String boundary = UUID.randomUUID().toString().replaceAll("-", "");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "multipart/form-data;boundary=" + boundary)
.POST(MultipartBodyPublisher.ofMultipart(data, boundary))
.uri(URI.create("http://jkorpela.fi/cgi-bin/echoraw.cgi"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println("\n Body: " + response.body());
}
private static CompletableFuture<Void> reactiveSearch(HttpClient client, URI url, String term) {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(url)
.build();
StringFinder finder = new StringFinder(term);
client.sendAsync(request, BodyHandlers.fromLineSubscriber(finder))
.exceptionally(ex -> {
finder.onError(ex);
return null;
});
return finder
.found()
.exceptionally(Http2Api::handleError)
.thenAccept(found -> handleResult(url, found));
}
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://http2.golang.org/serverpush"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler())
.thenApply(HttpResponse::body)
.thenAccept((b) -> System.out.println("\nMain resource:\n" + b))
.join();
asyncPushRequests.forEach(CompletableFuture::join);
System.out.println("\nFetched a total of " + asyncPushRequests.size() + " push requests");
}
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);
}
}
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/basic-auth"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
/**
* Test changing port.
*
* @throws Exception when an error occurs.
*/
@Test
@Disabled
public void testChangingPort() throws Exception {
System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory");
final MicroPiranha piranha = new MicroPiranha();
piranha.configure(new String[]{"--port", "8088"});
Thread thread = new Thread(piranha);
thread.start();
Thread.sleep(3000);
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8088/does-not-exist")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 404);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
piranha.stop();
Thread.sleep(3000);
}
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.proxy(ProxySelector.getDefault())
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample body"));
}
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
/**
* Test file not found.
*
* @throws Exception when an error occurs.
*/
@Test
public void testFileNotFound() throws Exception {
HttpServer server = createServer(8765);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/this_is_certainly_not_there")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 404);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
/**
* Test SO_TIMEOUT.
*/
@Test
public void testSoTimeout() {
DefaultHttpServer server = new DefaultHttpServer(
8765, new DefaultHttpServerProcessor(), 2000);
assertEquals(server.getSoTimeout(), 2000);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 200);
} catch (IOException | InterruptedException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
@Test
public void postAsync() {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8081/test/resource"))
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("ping!"))
.build();
CompletableFuture<HttpResponse<String>> completableFuture =
client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
completableFuture
.thenApplyAsync(HttpResponse::headers)
.thenAcceptAsync(System.out::println);
HttpResponse<String> response = completableFuture.join();
assertThat(response.statusCode()).isEqualTo(200);
}
@Test
public void postJson() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
Book book = new Book(1, "Java HttpClient in practice");
String body = objectMapper.writeValueAsString(book);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8081/test/resource"))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(200);
assertThat(objectMapper.readValue(response.body(), Book.class).id).isEqualTo(1);
}
@Test
public void basicAuthentication() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
String encodedAuth = Base64.getEncoder()
.encodeToString(("user" + ":" + "pass").getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8081/test/secure"))
.header("Authorization", "Basic " + encodedAuth)
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(200);
}
/**
* Obtain the latest release object from the repository.
* @param repositoryURL for the GitHub api
* @return the latest release or null
*/
public static Release getLatestRelease(String repositoryURL)
{
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(repositoryURL)).build();
try
{
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if(response.statusCode() == 200)
{
return parseResponse(response.body());
}
else
{
mLog.error("Error while fetching latest releases - HTTP:" + response.statusCode());
}
}
catch(IOException | InterruptedException e)
{
mLog.error("Error while detecting the current release version of JMBE library", e);
}
return null;
}
/**
* Test process method.
*
* @throws Exception when a serious error occurs.
*/
@Test
public void testProcess() throws Exception {
DefaultWebApplicationServer server = new DefaultWebApplicationServer();
HttpServer httpServer = new DefaultHttpServer(8180, server, false);
DefaultWebApplication application = new DefaultWebApplication();
application.setContextPath("/context");
application.addServlet("snoop", new TestSnoopServlet());
application.addServletMapping("snoop", "/snoop/*");
server.addWebApplication(application);
server.initialize();
server.start();
httpServer.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8180/context/snoop/index.html")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 200);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
httpServer.stop();
server.stop();
}
/**
* Ctor.
*/
public ApiClient() {
builder = HttpClient.newBuilder();
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JavaTimeModule());
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
URI baseURI = URI.create("http://petstore.swagger.io:80/v2");
scheme = baseURI.getScheme();
host = baseURI.getHost();
port = baseURI.getPort();
basePath = baseURI.getRawPath();
interceptor = null;
readTimeout = null;
responseInterceptor = null;
}
/**
* Test start method.
*
* @throws Exception when an error occurs.
*/
@Test
@Disabled
public void testStart() throws Exception {
System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory");
final MicroPiranha piranha = new MicroPiranha();
piranha.configure(new String[]{});
Thread thread = new Thread(piranha);
thread.start();
Thread.sleep(3000);
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/does-not-exist")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 404);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
piranha.stop();
Thread.sleep(3000);
}
/**
* Test processing.
*
* @throws Exception when an error occurs.
*/
@Test
public void testProcessing2() throws Exception {
HttpServer server = createServer(8765);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 200);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
private SafeFuture<BLSSignature> sign(final Bytes signingRoot) {
final String publicKey = blsPublicKey.getPublicKey().toString();
return SafeFuture.ofComposed(
() -> {
final String requestBody = createSigningRequestBody(signingRoot);
final URI uri = signingServiceUrl.toURI().resolve("/signer/sign/" + publicKey);
final HttpRequest request =
HttpRequest.newBuilder()
.uri(uri)
.timeout(timeout)
.POST(BodyPublishers.ofString(requestBody))
.build();
return HttpClient.newHttpClient()
.sendAsync(request, BodyHandlers.ofString())
.handleAsync(this::getBlsSignature);
});
}
public static void asyncGet(String uri) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.build();
CompletableFuture<HttpResponse<String>> responseCompletableFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
responseCompletableFuture.whenComplete((resp, t) -> {
if (t != null) {
t.printStackTrace();
} else {
System.out.println(resp.body());
System.out.println(resp.statusCode());
}
}).join();
}
@Test
public void testWebSocketConnection() throws Exception {
// given
final HttpClient httpClient = HttpClient.newHttpClient();
final Config config = Application.getInstance(Config.class);
final String uri = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket";
// when
Listener listener = new Listener() {
@Override
public void onOpen(WebSocket webSocket) {
connected = true;
}
};
httpClient.newWebSocketBuilder().buildAsync(new URI(uri), listener).join();
// then
assertThat(connected, equalTo(true));
}
private static void getAsync(){
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.GET() // default
.build();
/*
CompletableFuture<Void> cf =
httpClient.sendAsync(req, BodyHandlers.ofString())
.thenAccept(resp -> System.out.println("Response: " +
resp.statusCode() + " : " + resp.body()));
*/
CompletableFuture<String> cf =
httpClient.sendAsync(req, BodyHandlers.ofString())
.thenApply(resp -> "Server responded: " + resp.body());
System.out.println("The request was sent asynchronously...");
try {
System.out.println("CompletableFuture get: " +
cf.get(5, TimeUnit.SECONDS));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Exit the client...");
}
private static void push(){
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.GET()
.build();
CompletableFuture cf =
httpClient.sendAsync(req, BodyHandlers.ofString(), (PushPromiseHandler) HttpClientDemo::applyPushPromise);
System.out.println("The request was sent asynchronously...");
try {
System.out.println("CompletableFuture get: " + cf.get(5, TimeUnit.SECONDS));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Exit the client...");
}
public static void main(String[] args) throws IOException, InterruptedException {
String message = "Hello World from Java 11";
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.version(HttpClient.Version.HTTP_2)
.build();
UriBuilder builder = UriBuilder
.fromUri("https://api.telegram.org")
.path("/{token}/sendMessage")
.queryParam("chat_id", CHAT_ID)
.queryParam("text", message);
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(builder.build("bot" + TOKEN))
.timeout(Duration.ofSeconds(5))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
@Test
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<String>> futures = targets.stream()
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
.GET()
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(response -> response.body()))
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.join();
if (futures.get(0)
.get()
.contains("foo1")) {
assertThat(futures.get(0)
.get(), containsString("bar1"));
assertThat(futures.get(1)
.get(), containsString("bar2"));
} else {
assertThat(futures.get(1)
.get(), containsString("bar2"));
assertThat(futures.get(1)
.get(), containsString("bar1"));
}
}
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
.version(HttpClient.Version.HTTP_2)
.POST(BodyPublishers.ofString("Sample Post Request"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body();
System.out.println("httpPostRequest : " + responseBody);
}