Home > Net >  Java HttpHeaders - how to get user agent value?
Java HttpHeaders - how to get user agent value?

Time:10-03

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
headers.set("User-Agent", "Mozilla/5.0..."); //note - value hard coded

I am currently writing a JUnit test where I create a RestTemplate containing the above request headers.

I am hardcoding the user-agent header to be Mozilla currently, how can I add the actual user agent of from which the test is running here instead of hardcoding the value?

CodePudding user response:

Every HTTP client (or so called user agent) can define its own value for the User-Agent HTTP header. All major HTTP clients, like for example browsers or command-line tools like cURL and wget, do so.

Since you are in effect writing your own HTTP client via RestTemplate, it is up to you whether to define a value for that header or leave it undefined. If you choose to define the header, it should follow the rules given in the HTTP specification (RFC 7231, or the current version RFC 9110).

To further answer your question: It seems like there was some discussion about setting a default value for that header for Spring Boot applications but it seems like the default value approach has not been implemented.

  • Related