Generating and Reading from URLs - Java Network

Java examples for Network:URL

Introduction

Use the java.net.URL class to create a URL.

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {

  public static void main(String[] args) {
    try {/*from   w  w w  . j a  v  a 2 s  . com*/
      URL url1 = new URL("http://www.java.net");
      System.out.println(url1.toString());

      // Generate URL for pages with a common base
      URL url2 = new URL(url1, "search/node/jdk7");

      // Generate URL from different pieces of data
      URL url3 = new URL("http", "java.net", "search/node/jdk7");

      readFromUrl(url1);

    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }
  }

  public static void readFromUrl(URL url) {
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(
          url.openStream()));

      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
      }

      in.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Result


Related Tutorials