I\'m writing an app that connect to a website and read one line from it. I do it like this:
try{
URLConnection connection = new URL(\"www.example.com
Closing the BufferedReader is enough - this closes the underlying reader too.
Yishai posted a nice pattern for closing the streams (closing might throw another exception).
I'd use apache commons IO for this, as others have suggested, mainly IOUtils.toString(InputStream) and IOUtils.closeQuietly(InputStream):
public String readFromUrl(final String url) {
InputStream stream = null; // keep this for finally block
try {
stream = new URL(url).openConnection().getInputStream(); // don't keep unused locals
return IOUtils.toString(stream);
} catch (final IOException e) {
// handle IO errors here (probably not like this)
throw new IllegalStateException("Can't read URL " + url, e);
} finally {
// close the stream here, if it's null, it will be ignored
IOUtils.closeQuietly(stream);
}
}