Reputation: 275
i got some problems with my SpringBoot REST Controller. This simply does a http GET call to our database and should return a simple String / json. when i call the URL simply in my browser or via my angular 3 app, the response has some charset errors and i don't know, how to fix them. I suggest, it is a UTF-8 problem.
First to show you the output: this is how it comes from the Controller: MeinekestraÃe and it should be Meinekestraße
here is a part of my SpringBoot Controller:
@Controller
public class RecieverController {
@Value("${server}")
private String server;
@Value("${user.token}")
private String token;
@RequestMapping(value="/reciever", method=RequestMethod.GET, produces = "text/plain;charset=UTF-8")
@ResponseBody
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
public String getRecieverData(
@RequestHeader(value="Accept") String accept,
@RequestHeader(value="Host") String host) {
final String url = server + "/rest/client/profile";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Auth-Token", token); // user_token
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return response.getBody();
}}
I tried the following things, but nothing changed in the output.
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
or this
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
any other ideas what could be the problem? the database isnt the issue. Everything is stored correctly there.
Edit: this is the screenshot of the header from the output and a part from the json output:
The Problem could be solved by adding both
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
and this
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
Thanks @dienerd for helping me via chat
Upvotes: 9
Views: 13644
Reputation: 171
For the ones looking for a way to force encoding request/response in @RestController in a Spring Boot project.
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
is deprecated, in your application.yaml or application.properties use the following:
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
This did the trick for me.
Upvotes: 17