1.2. HttpClient 接口
HttpClient
接口表示最基本的HTTP请求执行要约。它不会对请求执行过程加上约束或一些特定的信息,并且保留连接管理,状态管理,认证和处理重定向的细节到各自的实现中。这会使它更方便的使用额外功能来装饰接口,如响应内容缓存。
通常来说, HttpClient
接口的实现负责处理特定方面的HTTP协议,比如重定向、身份认证处理、对连接的持久性和维持连接存活长短的决策之类的多个处理程序和策略接口实现的门面。 这使得用户能够有选择性的将一些自定义的,基于特定应用的实现来替换默认的。
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration( HttpResponse response, HttpContext context) { long keepAlive = super.getKeepAliveDuration(response, context); if (keepAlive == -1) { // Keep connections alive 5 seconds if a keep-alive value // has not be explicitly set by the server keepAlive = 5000; } return keepAlive; } }; CloseableHttpClient httpclient = HttpClients.custom() .setKeepAliveStrategy(keepAliveStrat) .build();
当CloseableHttpClient
类的一个实例不再被调用或即将超出连接管理器关联的范围时, 必须通过调用CloseableHttpClient#close()
方法来关闭它
CloseableHttpClient httpclient = HttpClients.createDefault(); try { <...> } finally { httpclient.close(); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/114103.html