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
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()
.