Java,HttpURLConnection处理CLOSE_WAIT连接。

问题描述 投票:0回答:1

我使用java HttpURLConnection进行REST调用。在使用所有的rest api工作(使用ant targets测试rest调用)后,我看到有很多socket连接处于'close_wait'状态。

我试着在HttpURLConnection的InputStream或OutputStream上调用close()方法,但仍然只有连接处于CLOSE_WAIT状态。

还有一个观察是,即使使用con.disconnect()方法,连接也没有被关闭。

请帮助我解决这个问题,因为CLOSE_WAIT连接表明软件出现了错误。

下面是get调用的代码。其他的POSTPUTDELETE调用也像'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();
            }       
        }

谢谢你

Mohan G

java httpurlconnection
1个回答
0
投票

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

它将不断地创建套接字,如果连接是多个,它将超过每个进程打开文件的最大限制,例如在linux中通常是1024。与其使用disconnect,不如总是关闭输入流,定义于 http.maxConnection 在java系统属性中,当达到极限时,系统会关闭空闲连接。

也请检查 javadoc 的HttpUrlConnection类和方法disconnect。

© www.soinside.com 2019 - 2024. All rights reserved.