簡體   English   中英

從Web服務返回InputStream時與HttpURLConnection斷開連接

[英]Disconnecting from HttpURLConnection when returning an InputStream from a Webservice

我有一個正在調用Swift集群的Web服務,發現與它的連接處於CLOSE_WAIT狀態,直到HA代理強行關閉連接並記錄事件后才被關閉,從而導致大量事件產生。

對此進行調查,我發現這是由於在完成連接后沒有與基礎HttpURLConnection斷開連接。

因此,我已經對大多數RESTful服務進行了必要的更改,但是我不確定在返回要從Web服務直接從Swift檢索的InputStream的情況下,應該如何與HttpURLConnection斷開連接。

在這種情況下,我不知道有什么最佳實踐,或者在流被消耗掉之后,誰能想到可以斷開的任何好主意?

謝謝。

我最后只是將InputStream包裝在一個對象中,該對象還存儲HttpURLConnection,並在完成讀取流后立即調用斷開連接方法

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;
            }
        }
    }

您不必這樣做。 HttpURLConnection底層的連接池應該在幾秒鍾的空閑時間(我認為是15s)后關閉底層TCP連接。 通過調用disconnect()您將完全禁用連接池,因為每次調用都需要一個新的連接,這會浪費更多的網絡和服務器資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM