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.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   * This example demonstrates how to insert custom request interceptor and an execution interceptor
53   * to the request execution chain.
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                  // Add a simple request ID to each outgoing request
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                  // Simulate a 404 response for some requests without passing the message down to the backend
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