View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
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   * This example demonstrates how to insert custom request interceptor and an execution interceptor
51   * to the request execution chain.
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                  // Add a simple request ID to each outgoing request
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                  // Simulate a 404 response for some requests without passing the message down to the backend
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