URLConnection.openStream is more powerful than URL.openStream : URLConnection « Network « Java Tutorial






Reading a Web resource's headers and content:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainClass {
  public static void main(String[] args) {
    try {

      URL url = new URL("http://www.java2s.com/");
      URLConnection urlConnection = url.openConnection();
      Map<String, List<String>> headers = urlConnection.getHeaderFields();
      Set<Map.Entry<String, List<String>>> entrySet = headers.entrySet();
      for (Map.Entry<String, List<String>> entry : entrySet) {
        String headerName = entry.getKey();
        System.out.println("Header Name:" + headerName);
        List<String> headerValues = entry.getValue();
        for (String value : headerValues) {
          System.out.print("Header value:" + value);
        }
        System.out.println();
        System.out.println();
      }
      InputStream inputStream = urlConnection.getInputStream();
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
      String line = bufferedReader.readLine();
      while (line != null) {
        System.out.println(line);
        line = bufferedReader.readLine();
      }
      bufferedReader.close();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
Header Name:Content-Length
Header value:329495

Header Name:X-Powered-By
Header value:ASP.NET

Header Name:ETag
Header value:"30d67746a17c71:11e5"

Header Name:null
Header value:HTTP/1.1 200 OK

Header Name:Date
Header value:Fri, 26 Jan 2007 17:02:42 GMT

Header Name:Accept-Ranges
Header value:bytes

Header Name:Content-Type
Header value:text/html

Header Name:Server
Header value:Microsoft-IIS/6.0

Header Name:Last-Modified
Header value:Mon, 04 Dec 2006 06:04:11 GMT

Header Name:Content-Location
Header value:http://www.java2s.com/index.htm








19.5.URLConnection
19.5.1.java.net.URLConnection
19.5.2.URLConnection.openStream is more powerful than URL.openStream
19.5.3.Header Viewer
19.5.4.Sending a POST Request with Parameters From a Java Class
19.5.5.Downloading a web page using URL and URLConnection classes
19.5.6.Get response header from HTTP request
19.5.7.Getting the Response Headers from an HTTP Connection
19.5.8.Getting the Cookies from an HTTP Connection
19.5.9.Preventing Automatic Redirects in a HTTP Connection
19.5.10.Sending a Cookie to an HTTP Server
19.5.11.Writing to a Web server
19.5.12.Identify yourself using HTTP Authentification