知识点

相关文章

更多

最近更新

更多

HttpClient CacheConfig缓存处理示例

2019-04-09 22:52|来源: 网路

HttpClient Cache提供了一个与HTTP / 1.1兼容的缓存层,可以与HttpClient一起使用 - Java相当于浏览器缓存。 以下示例使用HttpClient缓存库的CacheConfig

Maven依赖关系

我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中。

pom.xml 文件的内容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

HttpClient缓存示例

这是如何设置基本缓存HttpClient的简单示例。 按照配置,它将存储最多3000个缓存对象,其中每个对象的最大主体大小可能为10240字节。 我们配置CacheConfig并使用这个配置来创建HttpClient。 循环执行一次简单的HTTP GET请求3次,并期望最后两个请求将被缓存。

文件:HttpClientCachingExample.java -

import org.apache.http.client.cache.CacheResponseStatus;
import org.apache.http.client.cache.HttpCacheContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.CachingHttpClients;

import java.io.IOException;

/**
 * This example demonstrates how to use caching {@link CacheConfig}.
 */
public class HttpClientCachingExample {

    public static void main(String... args) throws IOException {

        CacheConfig cacheConfig = CacheConfig.custom()
                .setMaxCacheEntries(3000)
                .setMaxObjectSize(10240) // 10MB
                .build();

        CloseableHttpClient cachingClient = CachingHttpClients.custom()
                .setCacheConfig(cacheConfig)
                .build();

        for (int i = 0; i < 3; i++){
            HttpCacheContext context = HttpCacheContext.create();
            HttpGet httpget = new HttpGet("http://httpbin.org/cache");
            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = cachingClient.execute(httpget, context);
            try {
                System.out.println("----------------------------------------");
                CacheResponseStatus responseStatus = context.getCacheResponseStatus();
                switch (responseStatus) {
                    case CACHE_HIT:
                        System.out.println("A response was generated from the cache with " +
                                "no requests sent upstream");
                        break;
                    case CACHE_MODULE_RESPONSE:
                        System.out.println("The response was generated directly by the " +
                                "caching module");
                        break;
                    case CACHE_MISS:
                        System.out.println("The response came from an upstream server");
                        break;
                    case VALIDATED:
                        System.out.println("The response was generated from the cache " +
                                "after validating the entry with the origin server");
                        break;
                }
            } finally {
                response.close();
            }
        }
    }

}

执行上面示例代码,得到以下结果 -

Executing request GET http://httpbin.org/cache HTTP/1.1
----------------------------------------
The response came from an upstream server
Executing request GET http://httpbin.org/cache HTTP/1.1
----------------------------------------
The response was generated from the cache after validating the entry with the origin server
Executing request GET http://httpbin.org/cache HTTP/1.1
----------------------------------------
The response was generated from the cache after validating the entry with the origin server

相关问答

更多
  • 将jar文件拖到项目中,以便在Eclipse中看到它。 为了赋予Eclipse特殊的含义,请右键单击Eclipse内部的jar文件,然后选择Build Path - > Add to Build Path。 现在您的进口应该正确解决。 You drag the jar file to your project so you can see it inside Eclipse. To give it special meaning to Eclipse, right click on the jar file ...
  • 普遍的共识是你不需要(不应该)处理HttpClient。 许多密切参与其工作方式的人已经说明了这一点。 请参阅Darrel Miller的博客文章和相关的SO文章: HttpClient抓取导致内存泄漏以供参考。 我还强烈建议您阅读“ 使用ASP.NET设计Evolvable Web API”的HttpClient章节,了解引擎盖下的内容,特别是引用的“生命周期”部分: 尽管HttpClient间接地实现了IDisposable接口,但HttpClient的标准用法并不是在每个请求之后处理。 HttpCli ...
  • 绝对使用服务,以便您拥有API请求的中心位置。 我通常为每种类型的api提供一项服务,即/ products,/ orders等。我发现(作为例子)来自应用程序周围的组件可能会调用/ products中的端点,因此分离为服务会使代码更清洁。 我将这些服务放在CoreModule https://angular.io/guide/ngmodule-faq#coremodule中 。 以下是如何从服务使用api调用的示例,而不是直接来自组件。 https://www.concretepage.com/angul ...
  • 正如它在这里提到的: HttpClient从响应中获取图像 DefaultHttpClient / HttpClient得到的只有一个内容,在你的情况下它是一个HTML页面(服务于: http://www.mysite/login.jsp )。 你需要解析那个HTML页面并获得指定的img标签,而不是你只需要下载它(只需要重新发送login.jsp请求!)。 如果您下载验证码图像,则需要尽快获取该图像,否则可能会被试图登录的其他用户覆盖。 正如浏览器所做的那样,你需要以同样的方式,下载HTML,而不是解析它 ...
  • 我认为您说正在执行http get的网页上包含“下一个按钮”,当您在浏览器中查看网页并单击下一个按钮时,将显示该网站的下一页。 如果是这种情况,是的,http客户端可以做同样的事情。 但要了解http客户端未与您的Web浏览器集成。 但是您可以使用像jsoup这样的库来搜索从http get请求返回的源代码,以便为网站上的“下一页”提取网址,然后发出另一个http get来获取该资源。 假设您已经有http客户端的代码发出初始的http get请求,则不需要额外的api。 您只需在程序发现“下一个”资源的U ...
  • 您应该在Windows Phone上使用HttpWebRequest。 请看以下链接: http : //social.msdn.microsoft.com/Forums/wpapps/en-us/9b4c1ef2-853c-468a-bca8-97477a02583c/httpclient-for-windows-phone-8?forum=wpdevelop You should be using an HttpWebRequest on Windows Phone. See this link: ht ...
  • 您可以尝试在URL中为输入查询添加一个参数。 您可以关注我的另一篇文章: 为什么HttpClient总是给我相同的回复? You can try to add one more parameter to your input queries in URL. You can follow my another post: Why does the HttpClient always give me the same response?
  • 您需要添加Microsoft.Net.Http NuGet包。 You need to add the Microsoft.Net.Http NuGet package.
  • 可能你应该切换到WinHTTP并使用另一个HTTP缓存实现。 有两种.NET Framework使用的HTTP客户端API。 一个由WinINet提供,另一个由WinHTTP提供。 .NET Framework默认使用WinINet。 但是WinINet是为了在客户端应用程序中工作而开发的,并且它不能在服务器环境中工作。 MSDN上的Windows Internet页面的相关引用: 适用时 WinINet不支持服务器实现。 另外,它不应该从服务中使用。 对于服务器实现或服务使用Microsoft Windo ...
  • 在实现这样的HttpClient之前,您需要记住以下几点。 通过使用Singleton模式可以实现客户端的单个实例。 确保您使用线程在后台进行所有下载并且不使用UI线程。 维护所有下载请求的队列。 单个Activity可以有多个请求,可以在填充之前下载各种组件,如数据,图像等。 所有这些请求都需要排队并一个接一个地运行。 如果在HttpClient队列清除之前切换一个Activity,则应该清除队列,这样它就不会停止加载新活动的组件。 希望能帮助到你。 Here are a few things that ...