1

In my Java application, I set the default system locale (Locale.getDefault()) as Accept-Language header for the HTTP request to my tomcat web application. In my case, this is de_DE.

On server side, I try to get the locale by using request.getLocale(). But I only get an empty string.

If I set the Accept-Language to de, everything works fine.

Why does de_DE not work as Accept-Language header?

EDIT:

This is my client side code:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Accept-Language", Locale.getDefault().toString());

And this my server side code:

request.getLocale().toString(); //empty string
request.getHeader("Accept-Language"); //"de_DE"
Franz Deschler
  • 2,456
  • 5
  • 25
  • 39

2 Answers2

2

The correct format for language tags is de-DE. With a dash, not an underscore.

I guess it wouldn't be surprising if other webservers were more lenient and would accept de_DE to be equivalent, but Tomcat does not. For reference, Tomcat delegates this parsing to Locale.forLanguageTag(), which makes it clear that it expects format de-DE.

kumesana
  • 2,495
  • 1
  • 9
  • 10
0

As kumesana pointed out, Tomcat will use Locale.forLanguageTag() to convert the Accept-Language header value into a Locale. There is an opposite method to convert a Locale instance into the expected header String: toLanguageTag()

I would suggest using this rather than manually replacing underscore with hyphen, so your code would be like the following:

connection.setRequestProperty("Accept-Language", Locale.getDefault().toLanguageTag());

Mike Muske
  • 323
  • 1
  • 16