You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring WebClient调用text/html接口报UnsupportedMediaTypeException如何解决

问题根因

该异常由两个核心原因导致:

  1. Spring WebClient默认的JSON反序列化转换器仅支持application/json等标准JSON媒体类型,不支持处理text/html类型的响应
  2. 你当前收到的响应本身是HTML页面内容,不是结构化的JSON数据,无法直接映射到你定义的ServiceResponsePOJO类
解决方案

根据实际场景可以选择以下任意方案处理:

方案1:调整WebClient配置,让JSON转换器支持text/html类型(仅适用于响应内容实际是JSON,仅响应头Content-Type写错为text/html的场景)

在初始化WebClient时配置消息转换器,给Jackson2JsonDecoder增加text/html媒体类型的支持:

WebClient webClient = WebClient.builder()
    .exchangeStrategies(ExchangeStrategies.builder()
        .codecs(configurer -> {
            // 给JSON解码器添加text/html支持
            configurer.defaultCodecs().jackson2JsonDecoder(
                new Jackson2JsonDecoder(
                    new ObjectMapper(),
                    MediaType.APPLICATION_JSON,
                    MediaType.TEXT_HTML
                )
            );
        })
        .build())
    .build();

方案2:先取HTML字符串再自定义解析(适用于响应确实是HTML内容的场景)

你可以先将响应以字符串格式获取,再自行解析HTML提取需要的字段映射到ServiceResponse:

  1. 调用时先传String.class作为响应类型,直接获取完整HTML内容
// 调用现有方法直接拿HTML字符串
String htmlResponse = invokeService(
    endPointUrl, 
    httpMethod, 
    headers, 
    requestPayload, 
    requestPlayLoadClass, 
    String.class
);
  1. 引入Jsoup等HTML解析工具,提取需要的字段
    首先引入Jsoup依赖(Maven示例):
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.15.3</version>
</dependency>

然后解析HTML提取字段:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 解析HTML
Document doc = Jsoup.parse(htmlResponse);
String content = doc.selectFirst("body hr").nextSibling().toString();

ServiceResponse response = new ServiceResponse();
// 提取agent.systemdevice字段
Matcher deviceMatcher = Pattern.compile("agent\\.systemdevice: (.*?)<br>").matcher(content);
if (deviceMatcher.find()) {
    response.setSystemDevice(deviceMatcher.group(1));
}
// 其余字段按照实际规则自行匹配提取即可

方案3:协调服务提供方调整返回格式(长期最优方案)

如果可以联系到服务2的维护方,建议对方将响应改为标准的application/json类型,返回结构化的JSON数据,无需额外适配即可直接映射到POJO类。

内容的提问来源于stack exchange,提问作者ssg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:48:03