In Java, it is often necessary to retrieve the HTTP response header when working with APIs or web services. The HTTP response header contains important information about the response, such as the content type, encoding, and response code. In this blog post, we will explore a simple way to get the HTTP response header in Java.
Java provides a built-in class called HttpURLConnection, which is used to establish a connection to a URL and retrieve the data.
public Map<String,List<String>> getHeaderFields()
Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent the response-header field names. Each Map value is an unmodifiable List of Strings that represents the corresponding field values.
This method considers only response headers set or added via
- setHeader(java.lang.String, java.lang.String)
- addHeader(java.lang.String, java.lang.String)
- setDateHeader(java.lang.String, long)
- addDateHeader(java.lang.String, long)
- setIntHeader(java.lang.String, int) or
- addIntHeader(java.lang.String, int) respectively.
Java Example:
The following code snippet shows how to create an URLConnection object and retrieve the HTTP response header:
package crunchify.com.tutorials; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * @author Crunchify.com * Simple Way to Get HTTP Response Header in Java - conn.getHeaderFields() * */ public class CrunchifyHTTPResponseHeader { public static void main(String[] args) { try { URL crunchifyObject = new URL("https://crunchify.com"); URLConnection conn = crunchifyObject.openConnection(); Map<String, List<String>> map = conn.getHeaderFields(); System.out.println("Printing All Response Header for URL: " + crunchifyObject.toString() + "\n"); for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } System.out.println("\nGet Response Header By Key ...\n"); List<String> contentLength = map.get("Content-Length"); if (contentLength == null) { System.out.println("'Content-Length' doesn't present in Header!"); } else { for (String header : contentLength) { System.out.println("Content-Lenght: " + header); } } } catch (Exception e) { e.printStackTrace(); } } }
In this code snippet, we first create a URL object representing the URL we want to connect to. Finally, we retrieve the HTTP response header using the getHeaderFields()
method, which returns a Map object containing the header fields and their corresponding values.
We can then iterate through the Map object using a for loop and print out each header field and its value. This will give us a clear idea of what information the HTTP response header contains.
It is important to note that the getHeaderFields()
method returns a Map object where each key represents a header field and its value is a List of all the values for that field. This is because some header fields, such as the “Set-Cookie” field, can have multiple values.
In conclusion, retrieving the HTTP response header in Java is a simple task that can be accomplished using the built-in HttpURLConnection class. By using the getHeaderFields()
method, we can easily retrieve the header fields and their values and use them in our application as needed.
Other must read:
Java URL example: Getting text from URL
Output:
Printing All Response Header for URL: https://crunchify.com Transfer-Encoding : [chunked] null : [HTTP/1.1 200 OK] Server : [cloudflare] CF-Ray : [79f5bf52ea6eaa70-DFW] X-Content-Type-Options : [nosniff] Connection : [keep-alive] X-Kinsta-Cache : [HIT] X-Edge-Location-Klb : [1] Date : [Sun, 26 Feb 2023 03:55:49 GMT] CF-Cache-Status : [DYNAMIC] Strict-Transport-Security : [max-age=63072000; includeSubDomains; preload] NEL : [{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}] Report-To : [{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=QC8GDvDkbtoHpQUJfqPqowm0TACZvToi5DGIAraUXSoVebpKHgHkGIsFjgZF90vS7r%2BS%2Bkdk0XScg4sLhMr1weAbLgvRFY49CAzB7pCPdwwrZjFm%2BqUV3n5JQC3q6lk%3D"}],"group":"cf-nel","max_age":604800}] Vary : [Accept-Encoding] Ki-CF-Cache-Status : [BYPASS] ki-cache-type : [None] alt-svc : [h3=":443"; ma=86400, h3-29=":443"; ma=86400] ki-edge : [v=17.19] Link : [<https://crunchify.com/java-asynchronous-httpclient-overview-and-tutorial-sendasync/>; rel=shortlink] Content-Type : [text/html; charset=UTF-8] Get Response Header By Key ... 'Content-Length' doesn't present in Header! Process finished with exit code 0
Let me know if you have any question about this program.