HttpURLConnection implementation

前端 未结 6 1123
自闭症患者
自闭症患者 2020-12-09 10:22

I have read that HttpURLConnection supports persistent connections, so that a connection can be reused for multiple requests. I tried it and the only way to send a second PO

6条回答
  •  不知归路
    2020-12-09 10:31

    Abandoning streams will cause idle TCP connections. The response stream should be read completely. Another thing I overlooked initially, and have seen overlooked in most answers on this topic is forgetting to deal with the error stream in case of exceptions. Code similar to this fixed one of my apps that wasn't releasing resources properly:

    HttpURLConnection connection = (HttpURLConnection)new URL(uri).openConnection();
    InputStream stream = null;
    BufferedReader reader = null;
    try {
            stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
    
            // do work on part of the input stream
    
    } catch (IOException e) {
    
        // read the error stream
        InputStream es = connection.getErrorStream();
        if (es != null) {
            BufferedReader esReader = null;
            esReader = new BufferedReader(new InputStreamReader(es, Charset.forName("UTF-8")));
            while (esReader.ready() && esReader.readLine() != null) {
            }
            if (esReader != null)
                esReader.close();
        }
    
        // do something with the IOException
    } finally {
    
        // finish reading the input stream if it was not read completely in the try block, then close
        if (reader != null) {
            while (reader.readLine() != null) {
            }
            reader.close();
        }
    
        // Not sure if this is necessary, closing the buffered reader may close the input stream?
        if (stream != null) {
            stream.close();
        }
    
        // disconnect
        if (connection != null) {
            connection.disconnect();
        }
    }
    

    The buffered reader isn't strictly necessary, I chose it because my use case required reading one line at a time.

    See also: http://docs.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html

提交回复
热议问题