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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
*/ 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 = "https://www.java2blog.com"; URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // Get all header fields Map<String, List> 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.