问题描述: 在使用Apache Http客户端时,可能会遇到以下错误消息:“HttpHostConnectException:连接到[host:port]失败:连接超时。”这通常是因为没有可用的连接导致的。在默认情况下,Apache Http客户端库会为每个目标主机创建多个连接,但有时可能会遇到没有可用连接的情况。
解决方法: 下面是一种解决方法,可以通过配置Apache Http客户端来解决这个问题。
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.DefaultHttpClientConnectionManager;
public class CustomConnectionManager extends DefaultHttpClientConnectionManager {
public CustomConnectionManager() {
super();
}
@Override
public void closeIdleConnections(long idletime, TimeUnit tunit) {
// 不关闭空闲连接
}
}
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class CustomHttpClient {
private static CloseableHttpClient httpClient;
public static synchronized CloseableHttpClient getHttpClient() {
if (httpClient == null) {
httpClient = HttpClients.custom()
.setConnectionManager(new CustomConnectionManager())
.build();
}
return httpClient;
}
}
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = CustomHttpClient.getHttpClient();
HttpGet httpGet = new HttpGet("http://example.com");
HttpResponse response = httpClient.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
httpClient.close();
}
}
通过以上代码示例,我们可以自定义连接管理器,禁用关闭空闲连接的功能,从而解决Apache Http客户端中没有可用连接的问题。