【问题标题】:Apache HttpClient return cached body on conditional requestApache HttpClient 根据条件请求返回缓存的正文
【发布时间】:2016-08-23 15:26:45
【问题描述】:

我正在使用来自 Apache 的 HttpClient 的 CachingHttpClient 实现。并有以下情况:

我请求了一个资源,该资源返回了带有标头的响应: Cache-Control:max-age=5。 所以 CachingHttpClient 缓存了响应。

我正在使用 If-Modified-Since 对同一资源发出有条件的请求。我收到状态码为 304 No modified 的响应(顺便说一句,它甚至不检查服务器)。没有响应体。这很好,但我想访问缓存的正文,因为如果它没有更新,我想使用它。

问题是:

有没有一种方便的方法可以从第一次调用中访问缓存的响应?

(使用 org.apache.httpcomponents:httpclient,org.apache.httpcomponents:httpclient-cache;版本 4.5.2)

服务器端:

    @RequestMapping("/number")
        public int getNumber(HttpServletResponse response, HttpServletRequest request) {
            log.info("Number gen called");
            response.setHeader("Cache-Control", "max-age=" + 5);
            return random.nextInt();
        }

客户端:

HttpGet httpget = new HttpGet("http://localhost:8080/number");

httpget.setHeader("If-Modified-Since", java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME.
        format(ZonedDateTime.now(ZoneId.of("GMT")).minusSeconds(1)));

HttpResponse resp = httpClient.execute(httpget);
        log.info("code: " + resp.getStatusLine().getStatusCode());
        // here fails because no body on 2. call
String responseString = new BasicResponseHandler().handleResponse(resp);

Http 客户端初始化

    @Bean
    public HttpClient httpClient() {
        return CachingHttpClients.createMemoryBound();
    }

【问题讨论】:

    标签: caching apache-httpclient-4.x cache-control apache-commons-httpclient


    【解决方案1】:

    好的,如果我显式配置缓存,我也可以直接使用该缓存对象,所以这是一个典型的 RTFM 问题,我的错。

    @Bean
    public HttpCacheStorage httpCacheStorage() {
        CacheConfig cacheConfig = CacheConfig.custom()
                .setMaxCacheEntries(1000)
                .setMaxObjectSize(8192)
                .build();
        HttpCacheStorage cacheStorage = new BasicHttpCacheStorage(cacheConfig);
        return cacheStorage;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多