How do i Handle a "ñ" character that comes as a "@PathVariable" in a request, Spring Boot

Oscar Garcia :

I have a RESTController that has the following method:

@GetMapping(value = "/equipos/ciudad/{ciudad}", produces = {"application/json"})
public ResponseEntity<List<EquipoBean>> getEquiposByCiudad(@PathVariable(name = "ciudad") String ciudad) {
    return new ResponseEntity<>(service.getEquiposByCiudad(ciudad), HttpStatus.OK);
}

It works when i send normal characters even if there are multiple words with spaces between them, but when i send it the "ñ" character i get an Exception like this:

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:475) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:260) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

I tried googling around to search for the answer but i didn't get to the solution so i'm asking here, is there a way for me to set my RESTController to properly handle those types of special characters?

cassiomolin :

Your client is expected to URL-encode such character. So ñ becomes %C3%B1.


You seem to be using a Spanish city name as parameter. So I will use A Coruña as example. If your client is written in Java, you can use URLEncoder:

String url = "http://example.org?q=" + URLEncoder.encode("A Coruña", "UTF-8");

Starting with Java 10, you can use:

String url = "http://example.org?q=" + 
    URLEncoder.encode("A Coruña", StandardCharsets.UTF_8);

With that, A Coruña will be encoded to A+Coru%C3%B1a.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16117&siteId=1