I have a rest endpoint that returns content type text/html
.
How can I read it, in a Spring boot app and keep it as text/html
and return it?
I don't want to retrieve it as a String. I want it to remain as text/html
.
This works but as said I want to preserve the text/html.
This ends up turning it into a large string in the response.
ResponseEntity<String> response = restOperations.exchange(url, HttpMethod.GET, requestEntity, String.class);
If I try to just use Object:
ResponseEntity<Object> response = restOperations.exchange(url, HttpMethod.GET, requestEntity, Object.class);
I end up with error:
Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.Object] and content type [text/html] org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.Object] and content type [text/html] at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:124)
How could I resolve this?
Full code:
@SpringBootApplication
public class MySpringApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringApplication.class, args);
}
@Bean
public RestOperations restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(Duration.ofMillis(4000))
.setReadTimeout(Duration.ofMillis(4000))
.build();
}
}
@RestController
public class MyController {
private final String domain;
private final RestOperations restOperations;
public MyController(
@Value("${domain}") String domain,
RestOperations restOperations
) {
this.domain = domain;
this.restOperations = restOperations;
}
@GetMapping("/get")
public Object get(@PathVariable("name") String name) {
Map<String, String> params = new HashMap<String, String>(){{
put("name", name);
}};
String url = getEndPoint(domain, params);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_HTML);
HttpEntity<Object> requestEntity = new HttpEntity<>(headers);
ResponseEntity<Object> response = restOperations.exchange(url, HttpMethod.GET, requestEntity, Object.class);
// some other logic
return response.getBody();
}
private String getEndPoint(String endPoint, Map<String, String> params) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(endPoint);
return builder.buildAndExpand(params).toUriString();
}
}