Home > Java > javaTutorial > body text

How to Read URL Content into a String with Java?

Mary-Kate Olsen
Release: 2024-11-01 14:44:29
Original
625 people have browsed it

How to Read URL Content into a String with Java?

Reading URL Content into a String with Java

A common need in programming is to retrieve the contents of a URL and store them as a string. In Groovy, this task is simplified by the concise syntax:

String content = "http://www.google.com".toURL().getText();
Copy after login

However, finding an equivalent implementation in Java can prove to be more challenging. While Java provides multiple options for this task, many of them involve complex buffering and loop constructs.

Simplified Approach

Fortunately, since the initial request for a concise solution, Java has introduced a more straightforward approach:

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

This line utilizes the Scanner class to read the stream obtained from the URL, treating the entire stream as a single string.

Extended Implementation

If desired, a more complete implementation can be created as follows:

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() : "";
    }
}
Copy after login

This method takes a URL as an input and returns the corresponding string content.

The above is the detailed content of How to Read URL Content into a String with Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!