Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (10.2k points)

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.

1 Answer

0 votes
by (46k points)

Now that some time has passed since the original answer was accepted, there's a better approach:

String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();

If you want a slightly fuller implementation, which is not a single line, do this:

public static String readStringFromURL(String requestURL) throws IOException

{

    try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),

            StandardCharsets.UTF_8.toString()))

    {

        scanner.useDelimiter("\\A");

        return scanner.hasNext() ? scanner.next() : "";

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...