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