Home  >  Article  >  Java  >  How to Read URL Content into a String in Java?

How to Read URL Content into a String in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 16:16:01979browse

How to Read URL Content into a String in Java?

How to Read URL Content into String in Java

In Java, you can easily read the content of a URL into a String using the following approach:

<code class="java">import java.net.URL;
import java.util.Scanner;
import java.nio.charset.StandardCharsets;

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() : "";
    }
}</code>

This code uses a Scanner object to read the content of the URL. The Scanner object is configured to use the UTF-8 character set, which is the default encoding for HTTP requests. The useDelimiter("A") statement tells the Scanner to read the entire contents of the URL into a single String.

If you want a single-line implementation, here is an alternate approach:

<code class="java">String content = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\A").next();</code>

This single line of code uses the same principles as the previous implementation, but it's written on a single line for brevity.

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

Statement:
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