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  package org.apache.hc.client5.http.cache.example;
28  
29  import org.apache.hc.client5.http.cache.CacheContextBuilder;
30  import org.apache.hc.client5.http.cache.HttpCacheContext;
31  import org.apache.hc.client5.http.cache.HttpCacheEntry;
32  import org.apache.hc.client5.http.cache.RequestCacheControl;
33  import org.apache.hc.client5.http.impl.cache.CacheConfig;
34  import org.apache.hc.client5.http.impl.cache.CachingHttpClients;
35  import org.apache.hc.client5.http.impl.cache.HeapResourceFactory;
36  import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
37  import org.apache.hc.core5.http.ClassicHttpRequest;
38  import org.apache.hc.core5.http.HttpHost;
39  import org.apache.hc.core5.http.io.entity.EntityUtils;
40  import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
41  import org.apache.hc.core5.http.message.StatusLine;
42  
43  /**
44   * This is an example demonstrating how to control execution of cache
45   * operation and determine its outcome using the classic HTTP cache API.
46   */
47  public class ClientCacheControl {
48  
49      public static void main(final String[] args) throws Exception {
50  
51          final HttpHost target = new HttpHost("https", "www.apache.org");
52  
53          try (final CloseableHttpClient httpclient = CachingHttpClients.custom()
54                  .setCacheConfig(CacheConfig.custom()
55                          .setMaxObjectSize(200000)
56                          .setHeuristicCachingEnabled(true)
57                          .build())
58                  .setResourceFactory(HeapResourceFactory.INSTANCE)
59                  .build()) {
60  
61              final ClassicHttpRequest httpget1 = ClassicRequestBuilder.get()
62                      .setHttpHost(target)
63                      .setPath("/")
64                      .build();
65  
66              // Use default cache control
67              final HttpCacheContext context = CacheContextBuilder.create()
68                      .setCacheControl(RequestCacheControl.DEFAULT)
69                      .build();
70  
71              System.out.println("Executing request " + httpget1.getMethod() + " " + httpget1.getUri());
72              httpclient.execute(httpget1, context, response -> {
73                  System.out.println("----------------------------------------");
74                  System.out.println(httpget1 + "->" + new StatusLine(response));
75                  EntityUtils.consume(response.getEntity());
76                  System.out.println("Cache status: " + context.getCacheResponseStatus());
77                  System.out.println("Request cache control: " + context.getRequestCacheControlOrDefault());
78                  System.out.println("Response cache control: " + context.getResponseCacheControlOrDefault());
79                  final HttpCacheEntry cacheEntry = context.getCacheEntry();
80                  if (cacheEntry != null) {
81                      System.out.println("Cache entry resource: " + cacheEntry.getResource());
82                      System.out.println("Date: " + cacheEntry.getInstant());
83                      System.out.println("Expires: " + cacheEntry.getExpires());
84                      System.out.println("Last modified: " + cacheEntry.getLastModified());
85                  }
86                  return null;
87              });
88  
89              final ClassicHttpRequest httpget2 = ClassicRequestBuilder.get()
90                      .setHttpHost(target)
91                      .setPath("/")
92                      .build();
93  
94              // Ensure a custom freshness for the cache entry
95              context.setRequestCacheControl(RequestCacheControl.builder()
96                      .setMinFresh(100)
97                      .build());
98  
99              System.out.println("Executing request " + httpget2.getMethod() + " " + httpget2.getUri());
100             httpclient.execute(httpget2, context, response -> {
101                 System.out.println("----------------------------------------");
102                 System.out.println(httpget2 + "->" + new StatusLine(response));
103                 EntityUtils.consume(response.getEntity());
104                 System.out.println("Cache status: " + context.getCacheResponseStatus());
105                 System.out.println("Request cache control: " + context.getRequestCacheControlOrDefault());
106                 System.out.println("Response cache control: " + context.getResponseCacheControlOrDefault());
107                 final HttpCacheEntry cacheEntry = context.getCacheEntry();
108                 if (cacheEntry != null) {
109                     System.out.println("Cache entry resource: " + cacheEntry.getResource());
110                     System.out.println("Date: " + cacheEntry.getInstant());
111                     System.out.println("Expires: " + cacheEntry.getExpires());
112                     System.out.println("Last modified: " + cacheEntry.getLastModified());
113                 }
114                 return null;
115             });
116 
117             Thread.sleep(2000);
118 
119             final ClassicHttpRequest httpget3 = ClassicRequestBuilder.get()
120                     .setHttpHost(target)
121                     .setPath("/")
122                     .build();
123 
124             // Try to force cache entry re-validation
125             context.setRequestCacheControl(RequestCacheControl.builder()
126                     .setMaxAge(0)
127                     .build());
128 
129             System.out.println("Executing request " + httpget3.getMethod() + " " + httpget3.getUri());
130             httpclient.execute(httpget3, context, response -> {
131                 System.out.println("----------------------------------------");
132                 System.out.println(httpget3 + "->" + new StatusLine(response));
133                 EntityUtils.consume(response.getEntity());
134                 System.out.println("Cache status: " + context.getCacheResponseStatus());
135                 System.out.println("Request cache control: " + context.getRequestCacheControlOrDefault());
136                 System.out.println("Response cache control: " + context.getResponseCacheControlOrDefault());
137                 final HttpCacheEntry cacheEntry = context.getCacheEntry();
138                 if (cacheEntry != null) {
139                     System.out.println("Cache entry resource: " + cacheEntry.getResource());
140                     System.out.println("Date: " + cacheEntry.getInstant());
141                     System.out.println("Expires: " + cacheEntry.getExpires());
142                     System.out.println("Last modified: " + cacheEntry.getLastModified());
143                 }
144                 return null;
145             });
146         }
147 
148 
149     }
150 }