Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpServletRequest UTF-8 Encoding [duplicate]

I want to get my parameters from the request (characters with accents) but it doesn't work. I tried to user request.setCharacterEncoding("UTF-8") but it didn't work either.

I know that URLDecoder.decode(request.getQueryString(), "UTF-8") returns the right characters, but request.getParameterValues() doesn't work!

Does anyone have an idea?

like image 392
Carvallegro Avatar asked May 13 '13 17:05

Carvallegro


2 Answers

Paul's suggestion seems like the best course of action, but if you're going to work around it, you don't need URLEncoder or URLDecoder at all:

String item = request.getParameter("param");   byte[] bytes = item.getBytes(StandardCharsets.ISO_8859_1); item = new String(bytes, StandardCharsets.UTF_8);  // Java 6: // byte[] bytes = item.getBytes("ISO-8859-1"); // item = new String(bytes, "UTF-8"); 

Update: Since this is getting a lot of votes, I want to stress BalusC's point that this definitely is not a solution; it is a workaround at best. People should not be doing this.

I don't know exactly what caused the original issue, but I suspect the URL was already UTF-8 encoded, and then was UTF-8 encoded again.

like image 164
VGR Avatar answered Sep 21 '22 09:09

VGR


If you are using Apache Tomcat, request.setCharacterEncoding("UTF-8") only works with POST request.

For GET request, you need add URIEncoding="UTF-8" on your <Connector> in server.xml.

See more in FAQ/CharacterEncoding - Apache Tomcat wiki space.

like image 41
Paul Vargas Avatar answered Sep 21 '22 09:09

Paul Vargas