According to technical guide from Oracle Java, we should consume 
HttpURLConnection's error stream when IOException thrown

http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html

What can you do to help with Keep-Alive? Do not abandon a connection by 
ignoring the response body. Doing so may results in idle TCP connections. 
That needs to be garbage collected when they are no longer referenced.

If getInputStream() successfully returns, read the entire response body.

When calling getInputStream() from HttpURLConnection, if an IOException 
occurs, catch the exception and call getErrorStream() to get the response 
body (if there is any).

Reading the response body cleans up the connection even if you are not 
interested in the response content itself. But if the response body is long 
and you are not interested in the rest of it after seeing the beginning, 
you can close the InputStream. But you need to be aware that more data 
could be on its way. Thus the connection may not be cleared for reuse.

Here's a code example that complies to the above recommendation:

Here's the code example

try {
        URL a = new URL(args[0]);
        URLConnection urlc = a.openConnection();
        is = conn.getInputStream();
        int ret = 0;
        while ((ret = is.read(buf)) > 0) {
          processBuf(buf);
        }
        // close the inputstream
        is.close();} catch (IOException e) {
        try {
                respCode = ((HttpURLConnection)conn).getResponseCode();
                es = ((HttpURLConnection)conn).getErrorStream();
                int ret = 0;
                // read the response body
                while ((ret = es.read(buf)) > 0) {
                        processBuf(buf);
                }
                // close the errorstream
                es.close();
        } catch(IOException ex) {
                // deal with the exception
        }}

Does this applicable to Android platform? As I don't see such technique in 
most of the Android code example.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Android Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to