Java get all response header

How to get HTTP Response Header using URLConnection in Java

Here is a simple example how to get HTTP Response Header using URLConnection in Java.

Example

package com.admfactory.http; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HTTPHeaderExample < public static void main(String[] args) < try < System.out.println("Get HTTP Headers Example"); System.out.println(); URL obj = new URL("https://www.google.com"); URLConnection conn = obj.openConnection(); System.out.println("List all headers:"); Map> map = conn.getHeaderFields(); for (Map.Entry> entry : map.entrySet()) < System.out.println(entry.getKey() + ": " + entry.getValue()); >System.out.println(); System.out.println("Get Header by key:"); String server = conn.getHeaderField("Content-Type"); if (server == null) < System.out.println("Key 'Content-Type' is not found!"); >else < System.out.println("Content-Type: " + server); >> catch (Exception e) < e.printStackTrace(); >> >

Output

Get HTTP Headers Example List all headers: Transfer-Encoding: [chunked] null: [HTTP/1.1 200 OK] Alt-Svc: [quic=":443"; ma=2592000; v="37,36,35"] Server: [gws] P3P: [CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."] Date: [Fri, 05 May 2017 15:45:43 GMT] Accept-Ranges: [none] X-Frame-Options: [SAMEORIGIN] Cache-Control: [private, max-age=0] Vary: [Accept-Encoding] Set-Cookie: [NID=102=SzMiPmg23g5Gbl6ky752KYkMtIQ36ued0fGFreQlRm7hWQOOzQo2u_8hnou0xPIYufnzEKtwTgG7_UlY9MSu3cwL77FjkiM2ZN26MijiC391xycU5FqCwEqmL1_DbIhV; expires=Sat, 04-Nov-2017 15:45:43 GMT; path=/; domain=.google.ro; HttpOnly] Expires: [-1] X-XSS-Protection: [1; mode=block] Content-Type: [text/html; charset=ISO-8859-2] Get Header by key: Content-Type: text/html; charset=ISO-8859-2 

Источник

HTTP Response Header Retrieval: Simple Way to Get HTTP Response Header in Java – conn. getHeaderFields()

Simple Way to Get HTTP Response Header in Java - conn.getHeaderFields()

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.

Читайте также:  Bitrix options php модуль

Java provides a built-in class called HttpURLConnection, which is used to establish a connection to a URL and retrieve the data.

public Map> 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> map = conn.getHeaderFields(); System.out.println("Printing All Response Header for URL: " + crunchifyObject.toString() + "\n"); for (Map.Entry> entry : map.entrySet()) < System.out.println(entry.getKey() + " : " + entry.getValue()); >System.out.println("\nGet Response Header By Key . \n"); List 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.

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 : [] 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 : [; 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.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Источник

Как получить заголовок HTTP-ответа на Java

В этом примере показано, как получить значения заголовка Http-ответа в Java.

URL obj = new URL("http://mkyong.com"); URLConnection conn = obj.openConnection(); //get all headers Map> map = conn.getHeaderFields(); for (Map.Entry> entry : map.entrySet()) < System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); >//get header by 'key' String server = conn.getHeaderField("Server"); 

2. Пример HttpClient для Apache.

HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://mkyong.com"); HttpResponse response = client.execute(request); //get all headers Header[] headers = response.getAllHeaders(); for (Header header : headers) < System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); >//get header by 'key' String server = response.getFirstHeader("Server").getValue();

1. Пример подключения к URL-адресу

Смотрите полный пример, чтобы получить значение заголовков ответов через URLConnection.

package com.mkyong; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class ResponseHeaderUtil < public static void main(String[] args) < try < URL obj = new URL("http://mkyong.com"); URLConnection conn = obj.openConnection(); Map> map = conn.getHeaderFields(); System.out.println("Printing Response Header. \n"); for (Map.Entry> entry : map.entrySet()) < System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); >System.out.println("\nGet Response Header By Key . \n"); String server = conn.getHeaderField("Server"); if (server == null) < System.out.println("Key 'Server' is not found!"); >else < System.out.println("Server - " + server); >System.out.println("\n Done"); > catch (Exception e) < e.printStackTrace(); >> > 
Printing Response Header. Key : null ,Value : [HTTP/1.1 200 OK] Key : ETag ,Value : ["713cd-9b82-4dd6d789447c0"] Key : Content-Length ,Value : [39810] Key : Expires ,Value : [Fri, 24 May 2013 03:22:31 GMT] Key : Last-Modified ,Value : [Fri, 24 May 2013 02:22:31 GMT] Key : Connection ,Value : [Keep-Alive] Key : X-Powered-By ,Value : [W3 Total Cache/0.9.2.9] Key : Server ,Value : [Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635] Key : Pragma ,Value : [public] Key : Cache-Control ,Value : [public] Key : Date ,Value : [Fri, 24 May 2013 02:22:37 GMT] Key : Vary ,Value : [Accept-Encoding,Cookie] Key : Keep-Alive ,Value : [timeout=2, max=100] Key : Content-Type ,Value : [text/html] Key : Accept-Ranges ,Value : [bytes] Get Response Header By Key . Server - Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Done

2. Пример HttpClient для Apache

Это эквивалентный пример, но с использованием Apache HttpClient.

package com.mkyong; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class ResponseHeaderUtil < public static void main(String[] args) < try < HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://mkyong.com"); HttpResponse response = client.execute(request); System.out.println("Printing Response Header. \n"); Header[] headers = response.getAllHeaders(); for (Header header : headers) < System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); >System.out.println("\nGet Response Header By Key . \n"); String server = response.getFirstHeader("Server").getValue(); if (server == null) < System.out.println("Key 'Server' is not found!"); >else < System.out.println("Server - " + server); >System.out.println("\n Done"); > catch (Exception e) < e.printStackTrace(); >> >

Рекомендации

Читайте ещё по теме:

Источник

Как получить заголовок ответа HTTP в Java

В этом примере показано, как получить значения заголовка ответа Http в Java.

URL obj = new URL("/"); URLConnection conn = obj.openConnection(); //get all headers Map> map = conn.getHeaderFields(); for (Map.Entry> entry : map.entrySet()) < System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); >//get header by 'key' String server = conn.getHeaderField("Server");

2. Пример Apache HttpClient.

HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("/"); HttpResponse response = client.execute(request); //get all headers Header[] headers = response.getAllHeaders(); for (Header header : headers) < System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); >//get header by 'key' String server = response.getFirstHeader("Server").getValue();

1. Пример URLConnection

См. Полный пример, чтобы получить значение заголовков ответа через URLConnection.

package com.example; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class ResponseHeaderUtil < public static void main(String[] args) < try < URL obj = new URL("/"); URLConnection conn = obj.openConnection(); Map> map = conn.getHeaderFields(); System.out.println("Printing Response Header. \n"); for (Map.Entry> entry : map.entrySet()) < System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); >System.out.println("\nGet Response Header By Key . \n"); String server = conn.getHeaderField("Server"); if (server == null) < System.out.println("Key 'Server' is not found!"); >else < System.out.println("Server - " + server); >System.out.println("\n Done"); > catch (Exception e) < e.printStackTrace(); >> >
Printing Response Header. Key : null ,Value : [HTTP/1.1 200 OK] Key : ETag ,Value : ["713cd-9b82-4dd6d789447c0"] Key : Content-Length ,Value : [39810] Key : Expires ,Value : [Fri, 24 May 2013 03:22:31 GMT] Key : Last-Modified ,Value : [Fri, 24 May 2013 02:22:31 GMT] Key : Connection ,Value : [Keep-Alive] Key : X-Powered-By ,Value : [W3 Total Cache/0.9.2.9] Key : Server ,Value : [Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635] Key : Pragma ,Value : [public] Key : Cache-Control ,Value : [public] Key : Date ,Value : [Fri, 24 May 2013 02:22:37 GMT] Key : Vary ,Value : [Accept-Encoding,Cookie] Key : Keep-Alive ,Value : [timeout=2, max=100] Key : Content-Type ,Value : [text/html] Key : Accept-Ranges ,Value : [bytes] Get Response Header By Key . Server - Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Done

2. Пример Apache HttpClient

Это эквивалентный пример, но с использованием Apache HttpClient.

package com.example; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class ResponseHeaderUtil < public static void main(String[] args) < try < HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("/"); HttpResponse response = client.execute(request); System.out.println("Printing Response Header. \n"); Header[] headers = response.getAllHeaders(); for (Header header : headers) < System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); >System.out.println("\nGet Response Header By Key . \n"); String server = response.getFirstHeader("Server").getValue(); if (server == null) < System.out.println("Key 'Server' is not found!"); >else < System.out.println("Server - " + server); >System.out.println("\n Done"); > catch (Exception e) < e.printStackTrace(); >> >

Рекомендации

Источник

Оцените статью