【发布时间】:2015-07-31 06:44:09
【问题描述】:
我正在使用 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();
}
}
谢谢
莫汉G
【问题讨论】:
-
请发布您的代码。
-
我正在使用以下代码来读取 response.protected static String streamToString(InputStream in) throws IOException { StringBuffer out = new StringBuffer();字节[] b = 新字节[4096]; for (int n; (n = in.read(b)) != -1;) { out.append(new String(b, 0, n)); } 返回 out.toString();在清理部分(最后),代码是 while (bytesRead = contentsStream.read(current)) >= 0) { } } finally{ if (contentsStream != null){ contentsStream.close();通过此更改,我收到以下警告 java.io.IOException: stream is closed。请提出建议。