调用 RESTEasy Client Proxy 接口,如何指定端点将使用哪种 Content-type?

Calling a RESTEasy Client Proxy interface, how can I specify which Content-type the endpoint will consume?

我想通过二进制 PUT 到一个端点,该端点可以使用许多可能的 mime 类型之一。具体来说,我正在与 Apache Tika 服务器通信,该服务器可以接收 PDF 或 Word .docx 文件。

我已经设置了一个可以硬编码的客户端代理接口,比如 .docx mimetype:

public interface TikaClient {
    @PUT
    @Path("tika")
    @Consumes("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    Response putBasic(byte[] body);
}

这将在我调用它时起作用:

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(url);
TikaClient tikaClient = target.proxy(TikaClient.
Response response = tikaClient.putBasic(binaryFileData);

.....但是那个端点具体也可以采用 "text/plain" 或 "application/pdf".

我相信我可以指定多个@Consumes 选项:@Consumes({"text/plain", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})

但是它好像没有选对,我不知道怎么告诉它哪个文件是有问题的。

如前所述,您可以添加多个 MediaType。如果服务器接受不止一种媒体类型,他必须与客户端协商应该使用哪一种。客户端应该发送一个 Content-Type header 比如 Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document

要使用代理框架添加 Content-Type header,您必须选择:

  • @HeaderParam("Content-Type") 作为参数添加到您的 putBasic 方法。
  • 注册一个 ClientRequestFilter 将设置这个 header。

我不知道为什么,但是使用代理框架这对我不起作用。如果您使用标准客户端方式,它是有效的:

client.target(url)
.request()
.put(Entity.entity(binaryFileData,
  MediaType.valueOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document")));

服务器现在应该选择您正在使用的媒体类型。