[英]Resttemplate url response giving Invalid mime type
I am callling a url like below, but in the response i am getting the Invalid mime type "JSON; charset=utf-8": does not contain '/'我正在调用 url,如下所示,但在响应中我得到了 Invalid mime type "JSON; charset=utf-8": does not contain '/'
@RequestMapping("/")
public String hello(){
HttpHeaders headers = new HttpHeaders();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://XXXX/Query.ashx");
HttpEntity<?> entity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
entity,
String.class);
return response.getBody() ;
}
From postman i checked the response headers of the api, there we are getting Content-Type: JSON;从 postman 我检查了 api 的响应标头,我们得到 Content-Type:JSON; charset=utf-8, which i am getting here. charset=utf-8,我在这里。 How to handle this?, we we just want plain json response.如何处理?,我们只想要简单的 json 响应。
Use '@RestController' annotation使用“@RestController”注解
@Himanshu Kindly provide complete class information which contain class level annotations. @Himanshu 请提供完整的 class 信息,其中包含 class 级别注释。 Along with that question is Are you getting exception while calling shown api or restTemplate.exchange?除了这个问题之外,您在调用显示的 api 或 restTemplate.exchange 时是否遇到异常? . . Update your answer with complete stacktrace to find that.使用完整的堆栈跟踪更新您的答案以找到它。
I would prefer to use @GetMapping which is default to Json Response.我更喜欢使用默认为Json响应的 @GetMapping。 Please try that请尝试一下
You can completely control request/response parameters using RestTemplate interceptor(s):您可以使用 RestTemplate 拦截器完全控制请求/响应参数:
public class MimeInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
final ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.<what you want>);
ClientHttpResponse response = execution.execute(request, body);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.<what you want>);
return response;
}
}
And in code:在代码中:
...
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(List.of(new MimeInterceptor());
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.