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