HttpClient接口对于HTTP请求执行是关键。它对请求执行处理没有限制,而且舍弃连接管理,状态管理,认证和重定向到个人实现的那些方面的详细细节。这让使用附加功能修饰接口更容易了,例如response内容缓存。
HttpClient接口的实现通常也作为处理HTTP协议特定方面业务的Facade(参考Facade设计模式的定义),如重定向或认证处理或连接持久性决策和存活时间。这可以让用户有选择地使用自定义的程序在HttpClient上取代那些方面的默认实现。示例:
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();
1. HttpClient线程安全
HttpClient实现认为是线程安全的,推荐这个类的同个实例用于多个请求。
2. HttpClient资源释放
当CloseableHttpClient的实例不再需要并且即将退出连接管理器的范围, 它必须关闭。通过调用CloseableHttpClient的close()方法来关闭。
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
<...>
} finally {
httpclient.close();
}
Android 实现 HttpClient 请求Https