How to open and read from a URL in Java (with just the URL class)

On this blog I’ve shown several examples of how to read content from a URL using Java. In this example I’d like to show how you can open a URL and read content from that URL by just using the Java URL class.

(In other blog posts I demonstrate how to do something similar using the URLConnection and HttpURLConnection classes. You should be able to find any of these blog posts using the Search box of this blog.)

Java - open and read a URL with the URL class - source code

Here’s the source code for a complete Java class that demonstrates how to open a URL and read data from that URL:

import java.net.*;
import java.io.*;

/**
 *
 * A complete Java class that shows how to open a URL, then read data (text) from that URL,
 * just using the URL class, in combination with an InputStreamReader and BufferedReader.
 *
 * @author alvin alexander, devdaily.com.
 *
 */
public class UrlReader
{
  public static void main(String[] args) throws Exception
  {
    String urlString = "http://localhost:8080/";
    
    // create the url
    URL url = new URL(urlString);
    
    // open the url stream, wrap it an a few "readers"
    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

    // write the output to stdout
    String line;
    while ((line = reader.readLine()) != null)
    {
      System.out.println(line);
    }

    // close our reader
    reader.close();
  }
}

As you can see, it doesn’t take many lines of code to read data from a URL. Just create a new URL object, read data from the URL using the openStream method, wrap it in an InputStreamReader and BufferedReader, and loop through the output. How cool — that’s a lot of functionality for less than 10 lines of actual code.

Permalink

i would like to know how to read the content of a not found page.What i mean is that when a page is not found the server returns a 404 code.but still there is some content on the page the user is looking at.how do yuo get that content in Java..when i try the standard methods..if a URL is given for instance http://www.cplusplus.com/admin.html..nothing is printed by the method..even though if you try that URL on a browser you get an HTML page
cheers

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.