![](/img/trans.png)
[英]Connections leaking with state CLOSE_WAIT with java.net.HttpClient
[英]Java, HttpURLConnection handle CLOSE_WAIT connections
我正在使用 java HttpURLConnection 进行 REST 调用。 在使用所有其余 api 工作(使用 ant 目标测试其余调用)后,我看到有许多处于“CLOSE_WAIT”状态的套接字连接。
我尝试在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法,但连接仍然仅处于 CLOSE_WAIT 状态。
另一个观察结果是即使使用 con.disconnect() 方法也没有关闭连接。
请帮助我解决此问题,因为 CLOSE_WAIT 连接表明软件中存在错误。
下面是获取调用的代码。 其他 POST/PUT/DELETE 调用也类似于“get”
public void get(String url, Header[] headers,
NameValuePair[] data, ResponseHandler handler) throws HttpException {
HttpURLConnection con = null;
try
{
String query = null;
if (data != null) {
query = getQueryString(data);
}
URL obj;
if(query == null || query == "")
obj = new URL(url);
else
obj = new URL(url+"?"+query);
con = (HttpURLConnection) obj.openConnection();
setDoAuthentication(con);
con.setRequestMethod("GET");
con.setDoOutput(true);
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
con.setRequestProperty(headers[i].getName(), headers[i].getValue());
}
}
con.setRequestProperty("Accept-encoding", "gzip");
con.setRequestProperty("Authorization", this.auth);
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
if (handler!=null) handler.handleResponse(con); // in handleResponse(con) method, I am closing the con input stream
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new HttpException(new UnauthorizedException());
} else if (!is2xx(responseCode)) {
ErrorHandler errHandler = new ErrorHandler();
errHandler.handleResponse(con);
throw errHandler.getResult();
}
}
catch (MalformedURLException e) {
throw new HttpException(e);
}
catch (IOException e) {
handleSessionConnectionError(e, url);
}
finally {
con.disconnect();
}
}
谢谢
莫汉高
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.