繁体   English   中英

Java, HttpURLConnection 处理 CLOSE_WAIT 连接

[英]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();
            }       
        }

谢谢

莫汉高

调用con.disconnect()可能会导致问题。 看看这个链接链接

它会不断地创建套接字,如果连接是多个,它将​​超过每个进程打开的文件的最大限制,例如在 linux 中通常是 1024。而不是使用断开连接,始终关闭输入流, http.maxConnection定义的值java 系统属性中的http.maxConnection将在达到限制时完成关闭空闲连接的工作。

还要检查类中 HttpUrlConnection 的javadoc和方法断开连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM