Closing an HttpURLConnection before the response is complete

后端 未结 3 1579
春和景丽
春和景丽 2021-01-18 10:36

Background

I\'m using HttpURLConnection on the client side to consume a response in an HTTP streaming (server push) situation. Although the server may close the co

3条回答
  •  攒了一身酷
    2021-01-18 11:12

    It looks like this can't be done without altering the reading thread to poll using InputStream.available() and sleep for a short perdiod when there are no bytes available, all the while checking some flag to see if the thread should end.

    The solution is to just use Apache HTTP Components. By encapsulating the code for a GET request inside one class, this can be quite easily integrated into existing code.

    public class HttpGetConnection implements AutoCloseable {
        public HttpGetConnection(String url) throws IOException {
            client = new DefaultHttpClient();
            get = new HttpGet(url);
            response = client.execute(get);
            entity = response.getEntity();
        }
    
        public InputStream getContent() throws IOException {
            content = entity.getContent();
            return content;
        }
    
        @Override
        public void close() throws Exception {
            get.abort();
            try {
                content.close();
            }
            catch (IOException e) {
            }
        }
    
        private HttpClient client;
        private HttpGet get;
        private HttpResponse response;
        private HttpEntity entity;
        private InputStream content;
    }
    

    The loop in the original post can remain as is and the reading thread will die shortly after calling HttpGetConnection.close().

提交回复
热议问题