首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RESTEasy动态提供ContentType

RESTEasy动态提供ContentType
EN

Stack Overflow用户
提问于 2020-08-06 19:21:16
回答 1查看 144关注 0票数 0

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

接口:

代码语言:javascript
复制
@POST
@Path("api/files/upload/")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes()
FileUploadResponse uploadFile(byte[] file);

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

代码语言:javascript
复制
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,调用会失败,并返回HTTP400 (Bad Request):

代码语言:javascript
复制
@POST
@Path("api/files/upload/")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes()
FileUploadResponse uploadFile(byte[] file, @HeaderParam("Content-Type") String contentType);

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

我以为我可以删除@Consumes(),因为我自己设置了头文件,但是我得到了另一个错误:

代码语言:javascript
复制
java.lang.RuntimeException: RESTEASY004590: You must define a @Consumes type on your client method or interface, or supply a default

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

EN

回答 1

Stack Overflow用户

发布于 2020-08-07 06:12:36

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

代码语言:javascript
复制
@POST
@Path("api/files/upload/")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
FileUploadResponse uploadFile(byte[] file);

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

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

代码语言:javascript
复制
@POST
@Path("api/files/upload/")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
FileUploadResponse uploadFile(byte[] file, @Context HttpServletRequest request);

在实现方法中:

代码语言:javascript
复制
String contentType = request.getHeader("Content-Type");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63282482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档