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
28 package org.apache.hc.client5.http.examples;
29
30 import java.util.concurrent.Future;
31
32 import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
33 import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
34 import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
35 import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
36 import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
37 import org.apache.hc.client5.http.impl.ChainElement;
38 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
39 import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
40 import org.apache.hc.core5.concurrent.FutureCallback;
41 import org.apache.hc.core5.http.ContentType;
42 import org.apache.hc.core5.http.message.StatusLine;
43 import org.apache.hc.core5.http.nio.entity.DigestingEntityProducer;
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
52 public class AsyncClientMessageTrailers {
53
54 public final static void main(final String[] args) throws Exception {
55
56 final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
57 .setSoTimeout(Timeout.ofSeconds(5))
58 .build();
59
60 final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
61 .setIOReactorConfig(ioReactorConfig)
62 .addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", (request, entityProducer, scope, chain, asyncExecCallback) -> {
63
64 chain.proceed(
65 request,
66 entityProducer != null ? new DigestingEntityProducer("MD5", entityProducer) : null,
67 scope,
68 asyncExecCallback);
69 })
70 .build();
71
72 client.start();
73
74 final SimpleHttpRequest request = SimpleRequestBuilder.post("http://httpbin.org/post")
75 .setBody("some stuff", ContentType.TEXT_PLAIN)
76 .build();
77
78 System.out.println("Executing request " + request);
79 final Future<SimpleHttpResponse> future = client.execute(
80 SimpleRequestProducer.create(request),
81 SimpleResponseConsumer.create(),
82 new FutureCallback<SimpleHttpResponse>() {
83
84 @Override
85 public void completed(final SimpleHttpResponse response) {
86 System.out.println(request + "->" + new StatusLine(response));
87 System.out.println(response.getBody());
88 }
89
90 @Override
91 public void failed(final Exception ex) {
92 System.out.println(request + "->" + ex);
93 }
94
95 @Override
96 public void cancelled() {
97 System.out.println(request + " cancelled");
98 }
99
100 });
101 future.get();
102
103 System.out.println("Shutting down");
104 client.close(CloseMode.GRACEFUL);
105 }
106
107 }
108