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.atomic.AtomicLong;
31
32 import org.apache.hc.client5.http.classic.methods.HttpGet;
33 import org.apache.hc.client5.http.impl.ChainElement;
34 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
35 import org.apache.hc.client5.http.impl.classic.HttpClients;
36 import org.apache.hc.core5.http.ClassicHttpResponse;
37 import org.apache.hc.core5.http.ContentType;
38 import org.apache.hc.core5.http.EntityDetails;
39 import org.apache.hc.core5.http.Header;
40 import org.apache.hc.core5.http.HttpRequest;
41 import org.apache.hc.core5.http.HttpRequestInterceptor;
42 import org.apache.hc.core5.http.HttpStatus;
43 import org.apache.hc.core5.http.io.entity.EntityUtils;
44 import org.apache.hc.core5.http.io.entity.StringEntity;
45 import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
46 import org.apache.hc.core5.http.message.StatusLine;
47 import org.apache.hc.core5.http.protocol.HttpContext;
48
49
50
51
52
53 public class ClientInterceptors {
54
55 public static void main(final String[] args) throws Exception {
56 try (final CloseableHttpClient httpclient = HttpClients.custom()
57
58
59
60 .addRequestInterceptorFirst(new HttpRequestInterceptor() {
61
62 private final AtomicLong count = new AtomicLong(0);
63
64 @Override
65 public void process(
66 final HttpRequest request,
67 final EntityDetails entity,
68 final HttpContext context) {
69 request.setHeader("request-id", Long.toString(count.incrementAndGet()));
70 }
71 })
72
73
74
75 .addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", (request, scope, chain) -> {
76
77 final Header idHeader = request.getFirstHeader("request-id");
78 if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
79 final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie");
80 response.setEntity(new StringEntity("bad luck", ContentType.TEXT_PLAIN));
81 return response;
82 }
83 return chain.proceed(request, scope);
84 })
85 .build()) {
86
87 for (int i = 0; i < 20; i++) {
88 final HttpGet httpget = new HttpGet("http://httpbin.org/get");
89
90 System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
91
92 httpclient.execute(httpget, response -> {
93 System.out.println("----------------------------------------");
94 System.out.println(httpget + "->" + new StatusLine(response));
95 EntityUtils.consume(response.getEntity());
96 return null;
97 });
98 }
99 }
100 }
101
102 }
103