1

I want to consume html response using restTemplate and rerun that response to my html so i can add those content to my html page but getting below error tried so many alternatives but not luck

I want to consume every type of response and return that as it is to my html/jsp via ajax and render that content in a div.

HTML (ajax call) --- Spring MVC (rest call to 3rd party) --- application returns html

Code

@RequestMapping(value = "/xyz-service/**", method = {RequestMethod.GET, RequestMethod.PUT},produces="application/json;charset=UTF-8")
    public Object mirrorRest(HttpServletRequest request) {
        String url = request.getRequestURI();

        return restTemplate.getForObject("http://xyz-service:8080"+url , String.class);
    }

I am able to invoke my serive method that retuning html as respose but getting error

"Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.String] and content type [text/html;charset=UTF-8]"
]
Sandeep Bhardwaj
  • 1,310
  • 1
  • 18
  • 24
  • Did you checked this thread https://stackoverflow.com/questions/44176335/restclientexception-could-not-extract-response-no-suitable-httpmessageconverte? – Daniel Boncioaga Aug 23 '19 at 21:22

2 Answers2

0

The exception seem to have occurred because your request was missing the header parameters.

        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", "Bearer " + apikey);
        headers.set("Charset", "utf-8");
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Request> entity = new HttpEntity<Request>(
                    req, headers); //incase if your request have a request body

            try {

                ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); //if no request body you could simply use headers parameter directly
                logger.info(response.toString());
                return response.getBody().toString();

            } catch (HttpStatusCodeException exception) {
                logger.info("API failed"+exception);
                return null;
            }
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
eccentricCoder
  • 846
  • 1
  • 14
  • 35
-1

No you can't. An HTML page is not a json object: REST template is designed to consume RestServices. You should use a URLConnection from jdk

ivan.rosina
  • 368
  • 3
  • 9
  • There is nothing like a restTemplate cant return an html response. I have come across several cases where restTemplate is used to return html response. – eccentricCoder Jan 15 '23 at 11:32