我正在使用java HttpURLConnection进行REST调用。在使用所有rest api工作(使用ant目标测试rest调用)之后,我发现有许多套接字连接处于“CLOSE_WAIT”状态。
我尝试在HttpURLConnection的InputStream或OutputStream上调用close()方法,但连接仍然只处于CLOSE_WAIT状态。
另一个观察结果是con.disconnect()方法也没有关闭连接。
当CLOSE_WAIT连接指示软件中存在错误时,请帮助我解决此问题。
下面是get调用的代码。其他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();
}
}谢谢
莫汉G
https://stackoverflow.com/questions/30325616
复制相似问题