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