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

DropWizard迁移Quarkus后@Consumes兼容text/plain问题咨询

解决方案:Quarkus Resteasy-Reactive兼容text/plain请求(原DropWizard行为)

问题根源

DropWizard基于传统JAX-RS实现,当请求体参数为String类型时,会绕过@Consumes的Content-Type校验,直接将请求体转为字符串。而Quarkus的Resteasy-Reactive遵循严格的JAX-RS规范,会先校验请求头Content-Type是否匹配@Consumes配置,不匹配则返回415错误。

可行解决方案

1. 直接修改@Consumes注解(推荐)

这是最符合规范且无隐患的方式,在原有application/json基础上添加text/plain:

@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public Response handleRequest(String body) {
    // 业务逻辑
}

该方式明确声明接口支持的Content-Type,避免后续维护歧义。

2. 自定义MessageBodyReader(无需修改接口注解)

如果不想改动现有接口的注解配置,可以实现一个全局生效的MessageBodyReader,让String类型参数同时兼容两种Content-Type:

@Provider
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public class StringMultiTypeReader implements MessageBodyReader<String> {

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return String.class.equals(type);
    }

    @Override
    public String readFrom(Class<String> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                          MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
        return new String(entityStream.readAllBytes(), StandardCharsets.UTF_8);
    }
}

Quarkus会自动扫描并注册这个Provider,所有接收String请求体的接口都会自动兼容application/json和text/plain类型的请求,无需修改原有@Consumes配置。

3. 临时过渡方案(不推荐)

如果只是临时兼容需求,可以将@Consumes设为通配符*/*,允许所有Content-Type:

@Consumes(MediaType.WILDCARD)

但该方式会放宽接口的Content-Type校验,存在安全隐患,不建议长期使用。

全局配置说明

Quarkus 2.16.7.Final的Resteasy-Reactive没有提供全局关闭Content-Type校验的配置项,因为这违反JAX-RS规范,所以无法通过配置文件实现该需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:20:17