在包含文件和JSON的多部分请求中出现 "无法找到MessageBodyReader "错误

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

我有一个简单的Quarkus应用程序,它有一个POST资源。

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateContent(@MultipartForm MyRequest request) {
    bus.sendAndForget("request", request);
    return Response.accepted().build();
}

MyRequest是这样的。

public class MyRequest {
  @FormParam("template")
  @PartType(MediaType.APPLICATION_OCTET_STREAM)
  private byte[] template;

  @FormParam("data")
  @PartType(MediaType.TEXT_PLAIN)
  private Map<String, String> data;

  // Default constructor & getters
}

然后我用Postman发送以下内容

enter image description here

然后我得到了以下错误。

java.lang.RuntimeException: RESTEASY007545: Unable to find a MessageBodyReader for media type: text&#x2F;plain; charset=us-ascii and class type java.util.Map

如果我只发送模板,它就能正常工作,所以似乎JSON字符串由于某种原因不能被解析。

我想我已经有了所有需要的依赖关系,如

  • quarkus-resteasy-jackson(杰克逊)
  • 轻松的多部件供应商
  • resteasy-jackson2-provider)。

而且我也试过手动注册ResteasyJackson2Provider,并将数据属性的mediaType改为APPLICATION_JSON,但这并没有帮助。我错过了什么,或者我是否正确发送了JSON?

java deserialization quarkus
1个回答
2
投票

对于表单数据,只有文件和文本字段。正因为如此,在form-data中,任何类型仍然会被解释为textplain。然而,在请求过滤器中可以设置一个参数,然后再进行数据解析。

在请求过滤器中创建 ContainerRequestFilter:

@ApplicationScoped
@Provider
public class MyFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        // apply next only for your form-data path and ignore all the other requests
        final HttpRequest httpRequest = ResteasyContext.getContextData(HttpRequest.class);
        httpRequest.setAttribute("resteasy.provider.multipart.inputpart.defaultContentType", "application/json");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.