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.nio.ByteBuffer;
32  import java.nio.charset.StandardCharsets;
33  import java.util.concurrent.Future;
34  import java.util.concurrent.atomic.AtomicLong;
35  
36  import org.apache.hc.client5.http.async.AsyncExecCallback;
37  import org.apache.hc.client5.http.async.AsyncExecChain;
38  import org.apache.hc.client5.http.async.AsyncExecChainHandler;
39  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
40  import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
41  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
42  import org.apache.hc.client5.http.impl.ChainElement;
43  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
44  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
45  import org.apache.hc.core5.concurrent.FutureCallback;
46  import org.apache.hc.core5.http.ContentType;
47  import org.apache.hc.core5.http.EntityDetails;
48  import org.apache.hc.core5.http.Header;
49  import org.apache.hc.core5.http.HttpException;
50  import org.apache.hc.core5.http.HttpRequest;
51  import org.apache.hc.core5.http.HttpRequestInterceptor;
52  import org.apache.hc.core5.http.HttpResponse;
53  import org.apache.hc.core5.http.HttpStatus;
54  import org.apache.hc.core5.http.impl.BasicEntityDetails;
55  import org.apache.hc.core5.http.message.BasicHttpResponse;
56  import org.apache.hc.core5.http.nio.AsyncDataConsumer;
57  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
58  import org.apache.hc.core5.http.protocol.HttpContext;
59  import org.apache.hc.core5.io.CloseMode;
60  import org.apache.hc.core5.reactor.IOReactorConfig;
61  import org.apache.hc.core5.util.Timeout;
62  
63  /**
64   * This example demonstrates how to insert custom request interceptor and an execution interceptor
65   * to the request execution chain.
66   */
67  public class AsyncClientInterceptors {
68  
69      public static void main(final String[] args) throws Exception {
70  
71          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
72                  .setSoTimeout(Timeout.ofSeconds(5))
73                  .build();
74  
75          final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
76                  .setIOReactorConfig(ioReactorConfig)
77  
78                  // Add a simple request ID to each outgoing request
79  
80                  .addRequestInterceptorFirst(new HttpRequestInterceptor() {
81  
82                      private final AtomicLong count = new AtomicLong(0);
83  
84                      @Override
85                      public void process(
86                              final HttpRequest request,
87                              final EntityDetails entity,
88                              final HttpContext context) throws HttpException, IOException {
89                          request.setHeader("request-id", Long.toString(count.incrementAndGet()));
90                      }
91                  })
92  
93                  // Simulate a 404 response for some requests without passing the message down to the backend
94  
95                  .addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new AsyncExecChainHandler() {
96  
97                      @Override
98                      public void execute(
99                              final HttpRequest request,
100                             final AsyncEntityProducer requestEntityProducer,
101                             final AsyncExecChain.Scope scope,
102                             final AsyncExecChain chain,
103                             final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
104                         final Header idHeader = request.getFirstHeader("request-id");
105                         if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
106                             final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie");
107                             final ByteBuffer content = ByteBuffer.wrap("bad luck".getBytes(StandardCharsets.US_ASCII));
108                             final AsyncDataConsumer asyncDataConsumer = asyncExecCallback.handleResponse(
109                                     response,
110                                     new BasicEntityDetails(content.remaining(), ContentType.TEXT_PLAIN));
111                             asyncDataConsumer.consume(content);
112                             asyncDataConsumer.streamEnd(null);
113                         } else {
114                             chain.proceed(request, requestEntityProducer, scope, asyncExecCallback);
115                         }
116                     }
117 
118                 })
119 
120                 .build();
121 
122         client.start();
123 
124         final String requestUri = "http://httpbin.org/get";
125         for (int i = 0; i < 20; i++) {
126             final SimpleHttpRequest httpget = SimpleHttpRequests.get(requestUri);
127             System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
128             final Future<SimpleHttpResponse> future = client.execute(
129                     httpget,
130                     new FutureCallback<SimpleHttpResponse>() {
131 
132                         @Override
133                         public void completed(final SimpleHttpResponse response) {
134                             System.out.println(requestUri + "->" + response.getCode());
135                             System.out.println(response.getBody());
136                         }
137 
138                         @Override
139                         public void failed(final Exception ex) {
140                             System.out.println(requestUri + "->" + ex);
141                         }
142 
143                         @Override
144                         public void cancelled() {
145                             System.out.println(requestUri + " cancelled");
146                         }
147 
148                     });
149             future.get();
150         }
151 
152         System.out.println("Shutting down");
153         client.close(CloseMode.GRACEFUL);
154     }
155 
156 }
157