Getting Text from a URL - Java Network

Java examples for Network:URL

Description

Getting Text from 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 ww  w  .  j a va  2  s.c  om*/
      // Create a URL for the desired page
      URL url = new URL("http://hostname:80/index.html");

      // Read all the text returned by the server
      BufferedReader in = new BufferedReader(new InputStreamReader(
          url.openStream()));
      String str;
      while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
      }
      in.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
  }
}

Related Tutorials