How To Get HTTP Response Header In Java

In this post, we will see how to get HTTP response header in java. We have already seen how to send get or post request in java. I am using same example to demonstrate to get HTTP response header.
package org.arpit.java2blog.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
 * @author Arpit Mandliya
 */
public class HttpURLConnectionExample {

 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {

  HttpURLConnectionExample http = new HttpURLConnectionExample();

  // Sending get request
  http.sendingGetRequest();
 }

 // HTTP GET request
 private void sendingGetRequest() throws Exception {

  String urlString = "http://www.java2blog.com";

  URL url = new URL(urlString);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
                // Get all header fields
  Map<String, List<String>> map = con.getHeaderFields();

  System.out.println("Printing Response Header for URL: " + url.toString() + "\n");
  for (Map.Entry> entry : map.entrySet()) {
   System.out.println(entry.getKey() + " : " + entry.getValue());
  }

  // get specific field
  String date = con.getHeaderField("Date");
  System.out.println("\ngetting Date from response : " + date);

  // get specific field
  String server = con.getHeaderField("Server");
  System.out.println("\ngetting Server from response : " + server);
 }
}
When you run above code, you will get below output:
Printing Response Header for URL: http://www.java2blog.com

null : [HTTP/1.1 200 OK]
Transfer-Encoding : [chunked]
Vary : [Accept-Encoding]
Date : [Mon, 01 Aug 2016 17:58:23 GMT]
X-XSS-Protection : [1; mode=block]
Expires : [Mon, 01 Aug 2016 17:58:23 GMT]
Last-Modified : [Mon, 01 Aug 2016 17:49:36 GMT]
Accept-Ranges : [none]
Content-Type : [text/html; charset=UTF-8]
Server : [GSE]
X-Content-Type-Options : [nosniff]
Cache-Control : [private, max-age=0]

getting Date from response : Mon, 01 Aug 2016 17:58:23 GMT

getting Server from response : GSE


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012