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!