使用restTemplate使用Html响应

问题描述 投票:0回答:2

我想使用restTemplate使用html响应并重新运行对我的html的响应,这样我就可以将这些内容添加到我的html页面中,但遇到错误尝试了很多替代方案,但运气不佳

我想使用每种类型的响应,并通过ajax将其返回到我的html/jsp,并在div中渲染该内容。

HTML(ajax 调用)---Spring MVC(对第 3 方的其余调用)---应用程序返回 html

代码

@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);
    }

我能够调用我的服务方法,将 html 重新调整为响应,但出现错误

"Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.String] and content type [text/html;charset=UTF-8]"
]
spring-mvc resttemplate
2个回答
-1
投票

不,你不能。 HTML 页面不是 json 对象:REST 模板旨在使用 RestServices。 您应该使用 jdk 中的 URLConnection


-1
投票

Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.String] and content type [text/html;charset=UTF-8
似乎是由于
HttpMessageConverter
无法读取您的HTTP响应,因此失败并出现异常。

尝试将内容类型设置为

text/html

如果这不起作用,请尝试添加您自己的

HttpMessageConverter
,它可以读取和转换
text/html

发生异常似乎是因为您的请求缺少标头参数。

示例代码

        HttpHeaders headers = new HttpHeaders();

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

        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;
            }

此外,您可能想确保您正在使用 Jackson 依赖项。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
© www.soinside.com 2019 - 2024. All rights reserved.