I'm trying to find Java's equivalent to Groovy's:
String content = "http://www.google.com".toURL().getText();
I want to read content from a URL into string. I don't want to pollute my code with buffered streams and loops for such a simple task. I looked into apache's HttpClient but I also don't see a one or two line implementation.
Now that some time has passed since the original answer was accepted, there's a better approach:
If you want a slightly fuller implementation, which is not a single line, do this:
Additional example using Guava:
The following works with Java 7/8, secure urls, and shows how to add a cookie to your request as well. Note this is mostly a direct copy of this other great answer on this page, but added the cookie example, and clarification in that it works with secure urls as well ;-)
If you need to connect to a server with an invalid certificate or self signed certificate, this will throw security errors unless you import the certificate. If you need this functionality, you could consider the approach detailed in this answer to this related question on StackOverflow.
Example
outputs
Code
Now that more time has passed, here's a way to do it in Java 8:
This answer refers to an older version of Java. You may want to look at ccleve's answer.
Here is the traditional way to do this:
As @extraneon has suggested, ioutils allows you to do this in a very eloquent way that's still in the Java spirit:
Here's Jeanne's lovely answer, but wrapped in a tidy function for muppets like me: