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 package org.apache.hc.client5.http.examples;
28
29 import java.io.IOException;
30 import java.nio.CharBuffer;
31 import java.util.concurrent.Future;
32
33 import org.apache.hc.client5.http.async.methods.AbstractCharResponseConsumer;
34 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
35 import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
36 import org.apache.hc.core5.http.ContentType;
37 import org.apache.hc.core5.http.HttpException;
38 import org.apache.hc.core5.http.HttpHost;
39 import org.apache.hc.core5.http.HttpResponse;
40 import org.apache.hc.core5.http.Method;
41 import org.apache.hc.core5.http.message.StatusLine;
42 import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
43 import org.apache.hc.core5.io.CloseMode;
44 import org.apache.hc.core5.reactor.IOReactorConfig;
45 import org.apache.hc.core5.util.Timeout;
46
47
48
49
50 public class AsyncClientHttpExchangeStreaming {
51
52 public static void main(final String[] args) throws Exception {
53
54 final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
55 .setSoTimeout(Timeout.ofSeconds(5))
56 .build();
57
58 final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
59 .setIOReactorConfig(ioReactorConfig)
60 .build();
61
62 client.start();
63
64 final HttpHost target = new HttpHost("httpbin.org");
65 final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
66
67 for (final String requestUri: requestUris) {
68 final Future<Void> future = client.execute(
69 new BasicRequestProducer(Method.GET, target, requestUri),
70 new AbstractCharResponseConsumer<Void>() {
71
72 @Override
73 protected void start(
74 final HttpResponse response,
75 final ContentType contentType) throws HttpException, IOException {
76 System.out.println(requestUri + "->" + new StatusLine(response));
77 }
78
79 @Override
80 protected int capacityIncrement() {
81 return Integer.MAX_VALUE;
82 }
83
84 @Override
85 protected void data(final CharBuffer data, final boolean endOfStream) throws IOException {
86 while (data.hasRemaining()) {
87 System.out.print(data.get());
88 }
89 if (endOfStream) {
90 System.out.println();
91 }
92 }
93
94 @Override
95 protected Void buildResult() throws IOException {
96 return null;
97 }
98
99 @Override
100 public void failed(final Exception cause) {
101 System.out.println(requestUri + "->" + cause);
102 }
103
104 @Override
105 public void releaseResources() {
106 }
107
108 }, null);
109 future.get();
110 }
111
112 System.out.println("Shutting down");
113 client.close(CloseMode.GRACEFUL);
114 }
115
116 }