从Webservice返回InputStream时断开与HttpURLConnection的连接

时间:2013-03-11 22:36:14

标签: java sockets connection inputstream httpurlconnection

我有一个Web服务正在调用Swift集群,并发现与它的连接处于CLOSE_WAIT状态,并且在HA代理强制关闭连接并记录事件之前不会关闭,导致大量要生成的事件。

调查一下,我发现这是因为我们完成连接后没有断开与底层HttpURLConnection的连接。

所以我已经完成了对大多数RESTful服务的必要更改但是我不知道在我们返回一个InputStream的情况下我应该如何断开与HttpURLConnection的连接,我们直接从Swift中检索web服务。

在这个实例中应该做些什么样的最佳实践,我不知道,或者有人想到在流消耗后断开连接的任何好主意?

感谢。

2 个答案:

答案 0 :(得分:0)

我最终只是将InputStream包装在一个存储HttpURLConnection的对象中,并在读完流后调用disconnect方法

public class WrappedInputStream extends InputStream{

        InputStream is;
        HttpURLConnection urlconn;

        public WarppedInputStream(InputStream is, HttpURLConnection urlconn){
            this.is = is;
            this.urlconn = urlconn;
        }

        @Override
        public int read() throws IOException{
            int read = this.is.read();
            if (read != -1){
                return read;
            }else{
                is.close();
                urlconn.disconnect();
                return -1;
            }
        }

        @Override
        public int read(byte[] b) throws IOException{
            int read = this.is.read(b);
            if (read != -1){
                return read;
            }else{
                is.close();
                urlconn.disconnect();
                return -1;
            }
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException{
            int read = this.is.read(b, off, len);
            if (read != -1){
                return read;
            }else{
                is.close();
                urlconn.disconnect();
                return -1;
            }
        }
    }

答案 1 :(得分:0)

你不应该这样做。 {(1}}下面的连接池应该在一小段时间(我相信15秒)的空闲时间后关闭底层TCP连接。通过调用HttpURLConnection,您将完全禁用连接池,这会通过每次调用需要新连接来浪费更多网络和服务器资源。