Read data from a URL : HttpURLConnection « Network « Java Tutorial






import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class WebReader extends JFrame {
  JTextArea box = new JTextArea("Getting data ...");

  public WebReader() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600, 300);
    JScrollPane pane = new JScrollPane(box);
    add(pane);
    setVisible(true);
  }

  void getData(String address) throws Exception {
    setTitle(address);
    URL page = new URL(address);
    StringBuffer text = new StringBuffer();
    HttpURLConnection conn = (HttpURLConnection) page.openConnection();
    conn.connect();
    InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
    BufferedReader buff = new BufferedReader(in);
    box.setText("Getting data ...");
    String line;
    do {
      line = buff.readLine();
      text.append(line + "\n");
    } while (line != null);
    box.setText(text.toString());
  }

  public static void main(String[] arguments) throws Exception {
    WebReader app = new WebReader();
    app.getData("http://java2s.com");
  }
}








19.6.HttpURLConnection
19.6.1.Get the date of a url connection
19.6.2.Get the document expiration date
19.6.3.Get the document Last-modified date
19.6.4.Show the content type
19.6.5.Show the content length
19.6.6.Display request method
19.6.7.Get response code
19.6.8.Display response message
19.6.9.Display header information
19.6.10.Download and display the content
19.6.11.A Web Page Source Viewer
19.6.12.Reading from a URLConnection
19.6.13.Use BufferedReader to read content from a URL
19.6.14.Check if a page exists
19.6.15.Identify ourself to a proxy
19.6.16.Connect through a Proxy
19.6.17.java.net.Authenticator can be used to send the credentials when needed
19.6.18.Read data from a URL
19.6.19.Dump a page using the HTTPS protocol
19.6.20.Save URL contents to a file
19.6.21.Http connection Utilities
19.6.22.Parsing and formatting HTTP dates as used in cookies and other headers.
19.6.23.Last Modified
19.6.24.URL connection and proxy
19.6.25.Http Constants
19.6.26.Http Header Helper
19.6.27.A utility class for parsing HTTP dates as used in cookies and other headers