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.ExecChain;
34  import org.apache.hc.client5.http.classic.ExecChainHandler;
35  import org.apache.hc.client5.http.classic.methods.HttpGet;
36  import org.apache.hc.client5.http.impl.ChainElement;
37  import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
38  import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
39  import org.apache.hc.client5.http.impl.classic.HttpClients;
40  import org.apache.hc.core5.http.ClassicHttpRequest;
41  import org.apache.hc.core5.http.ClassicHttpResponse;
42  import org.apache.hc.core5.http.ContentType;
43  import org.apache.hc.core5.http.EntityDetails;
44  import org.apache.hc.core5.http.Header;
45  import org.apache.hc.core5.http.HttpException;
46  import org.apache.hc.core5.http.HttpRequest;
47  import org.apache.hc.core5.http.HttpRequestInterceptor;
48  import org.apache.hc.core5.http.HttpStatus;
49  import org.apache.hc.core5.http.io.entity.EntityUtils;
50  import org.apache.hc.core5.http.io.entity.StringEntity;
51  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
52  import org.apache.hc.core5.http.protocol.HttpContext;
53  
54  /**
55   * This example demonstrates how to insert custom request interceptor and an execution interceptor
56   * to the request execution chain.
57   */
58  public class ClientInterceptors {
59  
60      public static void main(final String[] args) throws Exception {
61          try (final CloseableHttpClient httpclient = HttpClients.custom()
62  
63                  // Add a simple request ID to each outgoing request
64  
65                  .addRequestInterceptorFirst(new HttpRequestInterceptor() {
66  
67                      private final AtomicLong count = new AtomicLong(0);
68  
69                      @Override
70                      public void process(
71                              final HttpRequest request,
72                              final EntityDetails entity,
73                              final HttpContext context) throws HttpException, IOException {
74                          request.setHeader("request-id", Long.toString(count.incrementAndGet()));
75                      }
76                  })
77  
78                  // Simulate a 404 response for some requests without passing the message down to the backend
79  
80                  .addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new ExecChainHandler() {
81  
82                      @Override
83                      public ClassicHttpResponse execute(
84                              final ClassicHttpRequest request,
85                              final ExecChain.Scope scope,
86                              final ExecChain chain) throws IOException, HttpException {
87  
88                          final Header idHeader = request.getFirstHeader("request-id");
89                          if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
90                              final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie");
91                              response.setEntity(new StringEntity("bad luck", ContentType.TEXT_PLAIN));
92                              return response;
93                          } else {
94                              return chain.proceed(request, scope);
95                          }
96                      }
97  
98                  })
99                  .build()) {
100 
101             for (int i = 0; i < 20; i++) {
102                 final HttpGet httpget = new HttpGet("http://httpbin.org/get");
103 
104                 System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
105 
106                 try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
107                     System.out.println("----------------------------------------");
108                     System.out.println(response.getCode() + " " + response.getReasonPhrase());
109                     System.out.println(EntityUtils.toString(response.getEntity()));
110                 }
111             }
112         }
113     }
114 
115 }
116