The accept-language header in request is usually a long complex string -
Eg.
Accept-Language : en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2
Is there a simple way to parse it in java? Or a API to help me do that?
The accept-language header in request is usually a long complex string -
Eg.
Accept-Language : en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2
Is there a simple way to parse it in java? Or a API to help me do that?
Here's an alternative way to parse the Accept-Language header which doesn't require a servlet container:
You can find an explanation of the Accept-Language header and associated q-values here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Many thanks to Karl Knechtel and Mike Samuel. Thier comments to the original question helped point me in the right direction.
ServletRequest.getLocale()
is certainly the best option if it is available and not overwritten as some frameworks do.For all other cases Java 8 offers
Locale.LanguageRange.parse()
as previously mentioned by Quiang Li. This however only gives back a Language String, not a Locale. To parse the language strings you can useLocale.forLanguageTag()
(available since Java 7):For the record, now it is possible with Java 8:
We are using Spring boot and Java 8. This works
In ApplicationConfig.java write this
and I have this list in my constants class that has languages that we support
and write the logic in the below class.
I would suggest using
ServletRequest.getLocales()
to let the container parse Accept-Language rather than trying to manage the complexity yourself.