Thursday, June 30, 2022

URLConnection : Get specific header field

 URLConnection class provides getHeaderField method, by using this you can get the value of specific header field.


public String getHeaderField(String name)
Returns the value of the named header field, or null if there is no such field in the header.

import java.net.URL;
import java.net.URLConnection;

public class Main {

  public static void main(String args[]) throws Exception {
    String resource = "https://self-learning-java-tutorial.blogspot.com";

    /* Construct URL object */
    URL url = new URL(resource);

    /* Open URLConnection to this URL */
    URLConnection conn = url.openConnection();

    String contentType = conn.getHeaderField("Content-Type");
    String tranferEncoding = conn.getHeaderField("Transfer-Encoding");
    String lastModified = conn.getHeaderField("Last-Modified");

    System.out.println("contentType : " + contentType);
    System.out.println("tranferEncoding : " + tranferEncoding);
    System.out.println("lastModified : " + lastModified);
  }
}

Sample Output
contentType : text/html; charset=UTF-8
tranferEncoding : chunked
lastModified : Mon, 18 May 2015 10:26:27 GMT

No comments:

Post a Comment

Java NIO - Overview

Java IO (Input/Output) is used to perform read and write operations. The  java.io package  contains all the classes required for input and o...