简体   繁体   中英

RestTemplate getForObject special characters into URL parameters

I am having problems when I try to call an endpoint using GET and passing a parameter into URL with special character like 'ñ':

Example:

parameters.add("name", "Añisc");
Person person = rest.getForObject(url.toUri(), Person.class, parameters);

Returns:

Error 502, Bad gateway

I've been reading possible solutions but none works for me. What can I do to send special characters in a property way?. I think that getForObject and url.toUri does the necessary encoding...

I have tried adding the following to tomcat config without luck:

URIEncoding="UTF-8"

Maybe you can use the other method of RestTemplate:

    final String oUrl = "http://myhost/name/{name}";
    final URI expanded = new UriTemplate(url).expand("Añisc");
    final String fUrl = URLDecoder.decode(expanded.toString(), "UTF-8");
    restTemplate.getForObject(fUrl, Object.class);

I mean, explading the URL yourself and put your desired encoding.

Try this

String query = "Añisc";
String uri = "http://localhost:8081/"; // example
String path = "name" //example

URI targetUrl = UriComponentsBuilder.fromUriString(url)
            .path(path)
            .queryParam("name", query)
            .build()
            .toUri();

restTemplate.getForObject(targetUrl, Person.class);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM