gpt4 book ai didi

java - httpClient:如何检查连接是否已被服务器端关闭

转载 作者:太空宇宙 更新时间:2023-11-04 11:54:30 25 4
gpt4 key购买 nike

我们连接到数据提供者并使用 HttpClient 以无限循环的方式不断读取 XML 数据。我们已经在Java代码中设置了连接超时和套接字超时。然而,当 HTTP 服务器端的连接关闭时,我们的应用程序不会抛出任何异常,只是卡在那里什么都不做。由于这种行为,当服务器启动时,Java 代码将不会重新连接。有没有办法查看套接字连接是否已被服务器端关闭?

此外,https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html提到了如何关闭STALE连接,但是仍然没有解决我们的问题。

提前非常感谢您!

代码片段:

private static final HttpClientConnectionManager CONN_MGR = new BasicHttpClientConnectionManager();

public boolean connectToServer() {
disconnect();

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
provider.setCredentials(AuthScope.ANY, credentials);

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15 * 1000)
.setSocketTimeout(15 * 1000).build();

HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
.setSSLSocketFactory(sslsf)
.setConnectionManager(CONN_MGR)
.setDefaultRequestConfig(requestConfig).build();

HttpGet request = new HttpGet(url);

try {
HttpResponse response = client.execute(request);
in = response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(in));
connected = true;

return true;
} catch (Exception re) {
LOGGER.error("error", re);
}

return false;
}

public void process() {
String xml = null;
while (!shuttingDown) {
try {

/* if we know the server side closed the connection already here
we can simply return and scheduler will take care of anything else. */

xml = reader.readLine();
lastSeen = System.currentTimeMillis();
if (StringUtils.isBlank(xml)) {
continue;
}
xml = xml.trim();

// processing XML here
} catch (IOException | NullPointerException ie) {
/* We see SocketTimeoutException relatively often and
* sometimes NullPointerException in reader.readLine(). */
if (!shuttingDown) {
if(!connectToServer()) {
break;
}
}
} catch (RuntimeException re) {
LOGGER.error("other RuntimeException", re);
break;
}
}

// the scheduler will start another processing.
disconnect();
}

// called by the scheduler periodically
public boolean isConnected() {
CONN_MGR.closeExpiredConnections();
CONN_MGR.closeIdleConnections(15, TimeUnit.SECONDS);
long now = System.currentTimeMillis();
if (now - lastSeen > 15000L) {
LOGGER.info("call disconnect() from isConnected().");
disconnect();
}

return connected;
}

最佳答案

我认为随着java 1.7中引入自动资源管理

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

已经注意清理过时的连接,即使在最坏的情况下,实现提供商也通过监视连接来仔细处理

Apache HttpClient 使用 HttpClientConnectionManager 和其他实用程序类来完成清理过时连接的工作。

关于java - httpClient:如何检查连接是否已被服务器端关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41488814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com