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?
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
.
The problem is that as the exception says ñ
cannot be present in a valid URL. The RFC defines a very specific set of characters that can be allowed and ALL other characters need to be URL-encoded.
So the solution should be that whoever is calling your API needs to url-encode their request and your service will work just fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.