Java http headers get

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-запроса в Java

В этом примере показано, как получить заголовки HTTP-запроса в Java. Чтобы получить заголовки HTTP-запроса, вам понадобится этот класс HttpServletRequest :

1. Примеры HttpServletRequest

1.1 Loop over the request header’s name and print out its value.

package com.example.web.utils; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; public class WebUtils < private MapgetHeadersInfo(HttpServletRequest request) < Mapmap = new HashMap(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) < String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); >return map; > >

Пример запроса заголовков:

1.2 Get the “user-agent” header only.

package com.example.web.utils; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; public class WebUtils < private String getUserAgent(HttpServletRequest request) < return request.getHeader("user-agent"); >>

Пример пользовательского агента:

Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

2. Spring MVC Пример

В Spring MVC вы можете @Autowired HttpServletRequest напрямую в любой управляемый компонент Spring.

package com.example.web.controller; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/site") public class SiteController < @Autowired private HttpServletRequest request; @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView getDomain(@PathVariable("input") String input) < ModelAndView modelandView = new ModelAndView("result"); modelandView.addObject("user-agent", getUserAgent()); modelandView.addObject("headers", getHeadersInfo()); return modelandView; >//get user agent private String getUserAgent() < return request.getHeader("user-agent"); >//get request headers private Map getHeadersInfo() < Mapmap = new HashMap(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) < String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); >return map; > >

Объявите эту зависимость в pom.xml , если HttpServletRequest не может найти.

 javax.servlet servlet-api 2.5 

Источник

Читайте также:  Python посмотреть все методы объекта

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.

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.

Читайте также:  What are servlets and jsp in java

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 Header

The following code calls the methods from URLConnection to find out the HTTP header properties.

import java.net.URL; import java.net.URLConnection; import java.util.Date; //from j av a2s .c o m public class Main < public static void main(String args[]) throws Exception < URL u = new URL("http://www.java2s.com"); URLConnection uc = u.openConnection(); System.out.println("Content-type: " + uc.getContentType()); System.out.println("Content-encoding: " + uc.getContentEncoding()); System.out.println("Date: " + new Date(uc.getDate())); System.out.println("Last modified: " + new Date(uc.getLastModified())); System.out.println("Expiration date: " + new Date(uc.getExpiration())); System.out.println("Content-length: " + uc.getContentLength()); > > 

The code above generates the following result.

Get HTTP connnection header fields

The following code reads out the http header. It creates a URL pointing to java2s.com frist. And then create URLConnection from the URL . After that it calls the getHeaderFields() method. getHeaderFields() method returns a map. In that map the key is the HTTP header key and the value is a List which is the HTTP header value.

import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.Set; /*from ja va 2 s . c o m*/ public class Main < public static void main(String[] args) throws Exception < URL url = new URL("http://www.java2s.com/"); URLConnection urlConnection = url.openConnection(); Map> headers = urlConnection.getHeaderFields(); Set> entrySet = headers.entrySet(); for (Map.Entry> entry : entrySet) < String headerName = entry.getKey(); System.out.println("Header Name:" + headerName); List headerValues = entry.getValue(); for (String value : headerValues) < System.out.print("Header value:" + value); > System.out.println(); > > > 

The code above generates the following result.

The following code uses Iterator to get the HTTP header values.

import java.net.URL; import java.net.URLConnection; import java.util.Iterator; import java.util.List; import java.util.Map; /*from j a v a2s . c o m*/ public class Main < public static void main(String[] args) throws Exception < URL url = new URL("http://www.java2s.com/index.html"); URLConnection connection = url.openConnection(); Map responseMap = connection.getHeaderFields(); for (Iterator iterator = responseMap.keySet().iterator(); iterator.hasNext();) < String key = (String) iterator.next(); System.out.println(key + " , "); > > > > 

The code above generates the following result.

Get field and get value

The following code finds out the HTTP header by calling getHeaderFieldKey and getHeaderField .

import java.net.URL; import java.net.URLConnection; //from j ava 2s .com public class Main < public static void main(String[] argv) throws Exception < URL url = new URL("http://java2s.com"); URLConnection conn = url.openConnection(); for (int i = 0;; i++) < String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); System.out.println(headerName); System.out.println(headerValue); if (headerName == null && headerValue == null) < System.out.println("No more headers"); break; > > > > 

Next chapter.

What you will learn in the next chapter:

Источник

How to get HTTP Request Header In Java

In this post , we will see how to get HTTP request header in java. Sometimes, you want to print request header values.
It is very simple to do it. You first need to get request object, then call getHeaderFields() on it to get all request header values.

Spring MVC:

If you are using Spring MVC, then you can use @Autowired annotation to get request object in controller.

@ RequestMapping ( value = «/countries» , method = RequestMethod . GET , headers = «Accept=application/json» )

You will get output as below:

user — agent : Mozilla / 5.0 ( Macintosh ; Intel Mac OS X 10_9_5 ) AppleWebKit / 537.78.2 ( KHTML , like Gecko ) Safari / 522.0

Was this post helpful?

Share this

Author

How to check if session exists or not in java

In this post, we will see how to check if HTTP session exists or not in java. Sometimes you need to check if session already exists or not and based on that perform some operations. If you use below code to get the session: [crayon-64b6efbe2e0cc532697205/] You will never get above session object as null because […]

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. [crayon-64b6efbe2d5b7158133127/] [crayon-64b6efbe2d5c1093499898/] When you run above code, you will get below output: [crayon-64b6efbe2d5c3589361132/] Was this post […]

How to send HTTP request GET/POST in Java

Table of ContentsHttpURLConnection example:Get Url:Post URL: In this post, we will see how to send HTTP Get/Post in java. There are many times when you need to send http get or post request. You can use HttpURLConnection for sending get/post request in java. It belongs to java.net package. HttpURLConnection example: We are going to send […]

Источник

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