英文:
Java Spring RestTemplate getForObject response not decoded properly
问题 {#heading}
我正在尝试在我的Spring Boot应用程序中使用RestTemplate类执行HTTP GET请求,该请求在Postman中可以正常执行。
这是我用于发送请求的代码:
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
当我执行这个代码时,响应变量中只包含奇怪的字符。
我最初的想法是我使用了错误的编码。
在Postman中看到的响应表明正确的编码是UTF-8,所以我添加了这段代码:
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
我还以为我使用了错误的"Accept"头部,所以我也添加了这段代码:
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.ALL_VALUE));
restTemplate.setInterceptors(interceptors);
这两个调整都没有解决问题。
是否有其他方法可以解决这个问题?
如果需要,我可以提供更多信息!
提前感谢。
英文:
I am trying to execute a HTTP GET request that I can execute properly in Postman in my Spring Boot application using the RestTemplate class.
This is the code I am using to send the request:
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
When I execute this the response variable contains only weird characters.
My initial thought was that I was using the wrong encoding.
The response I see in Postman indicates that the correct encoding is UTF-8, so I added this code:
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
I also though I was using the wrong "Accept" header, so I also added this code:
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.ALL_VALUE));
restTemplate.setInterceptors(interceptors);
Both these adjustments do not fix the issue.
Is there any other way to fix this?
I am happy to provide more info if needed!
Thanks in advance.
答案1 {#1}
得分: 0
这是因为响应大小对于我的Spring应用程序来说太大了。我不得不使用WebClient类,并使用'ExchangeStrategies':
int size = 100000 * 1024;
ExchangeStrategies strategies = ExchangeStrategies.builder()
.codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size))
.build();
此外,我还需要在application.yml文件中设置以下属性:
spring:
codec:
max-in-memory-size: 100MB
这两个调整解决了我的请求问题。 英文:
The reason for this was that the response size was too big for my Spring Application.
I had to use the WebClient class using the 'ExchangeStrategies':
int size = 100000 * 1024;
ExchangeStrategies strategies = ExchangeStrategies.builder()
.codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size))
.build();
Also I had to set this property in the application.yml file:
spring:
codec:
max-in-memory-size: 100MB
These two adjustments fixed the request for me.