【问题标题】:RESTEasy provide ContentType dynamicallyRESTEasy 动态提供 ContentType
【发布时间】:2020-08-06 11:21:16
【问题描述】:

我有一个使用代理接口实现的 RESTEasy 客户端 (3.6.2.Final),我想在其中调用 WS 来上传文件。如果我定义一个修复 Content-Type,调用会正常工作,但如果我想自己设置一个,调用会失败。

界面:

@POST
@Path("api/files/upload/")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes()
FileUploadResponse uploadFile(byte[] file);

在实例化代理时,我提供了基本身份验证:

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://..."));
target.register(new BasicAuthentication("username", "password"));
ApiInterface api = target.proxy(ApiInterface.class);

像这样调用有效,但标头中的 Content-Type 是通用的 * / *

如果我像这样添加 HeaderParam,调用将失败并显示 HTTP 400(错误请求):

@POST
@Path("api/files/upload/")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes()
FileUploadResponse uploadFile(byte[] file, @HeaderParam("Content-Type") String contentType);

我检查了 HTTP 调用,并且 Content-Type 在那里出现了两次:一次是 * / *,另一次是“application/pdf”(我在调用 uploadFile 时提供的那个)。

我以为我可以删除@Consumes(),因为我自己设置了标题,但后来又出现了另一个错误:

java.lang.RuntimeException: RESTEASY004590: You must define a @Consumes type on your client method or interface, or supply a default

根据我发送的文档,每次调用的 Content-Type 都会有所不同。 RESTEasy中没有办法将其定义为参数吗?

【问题讨论】:

    标签: java wildfly jax-ws resteasy


    【解决方案1】:

    您可以将Consumes 设置为通配符内容类型:

    @POST
    @Path("api/files/upload/")
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
    FileUploadResponse uploadFile(byte[] file);
    

    这将允许该方法接受任何内容类型。

    如果你得到什么类型的内容很重要,那么在你的方法中你可以检查提供的类型:

    @POST
    @Path("api/files/upload/")
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
    FileUploadResponse uploadFile(byte[] file, @Context HttpServletRequest request);
    

    并在实现方法中:

    String contentType = request.getHeader("Content-Type");
    

    【讨论】:

    • 非常感谢您的回答!也许这个问题并不清楚,但我没有处理电话,我是打电话的客户。我不想获取 Content-Type 标头,而是想设置它。我的问题是,如果我设置它,@Consumes 也在设置它,所以有 2 个标头并且 HTTP 请求无效。
    猜你喜欢
    • 2016-08-02
    • 2020-09-16
    • 2018-09-24
    • 2019-06-22
    • 2012-09-13
    • 2016-10-20
    • 2018-05-30
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多