我正在构建一个 REST 客户端来访问需要授权 header 的服务,但我不知道如何实现它

I'm building a REST client to access a service that requires an Authorization header but I don't know how ti implement that

我一直在做很多 SOAP,但在 REST 方面我是个新手。我正在构建一个客户端来访问需要我包含授权令牌的服务。它需要在 header 中,但我已经浏览了我在线购买的一本 PACKT 书籍和网站上的 2.17 用户指南。我想不通的是如何添加授权 header。任何人都可以帮助我或指出其中包含示例的文档。

谢谢, 罗伯·坦纳

tl;博士

只需调用header on the Invocation.Builder

Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().header("Authorization", "AuthValue").get();

查看部分 5.3.3 - 5.3.5 in the User Guide

可能有点令人困惑的是,您将看到的大多数示例都使用了方法链接,因此您看不到这些方法调用返回的所有实际类型,这使得查找变得困难正确的文档。

基本上,当您调用 request() on the WebTarget, you get back an Invocation.Builder

Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Invocation.Builder builder = target.request();

如果您查看我链接到的 Invocation.Builder Javadoc,您会发现一堆可以链接以构建请求的方法。其中一种方法是header(name, value)。在那里你可以设置 header

builder = builder.header("Authorization": "Some value");

完成构建后,您可以通过调用 buildXxx(), which returns in Invocation, from which you can invoke() 请求之一来构建请求。

Response response = builder.buildGet().invoke();

如果您查看 Invocation.Builder API,您会发现它扩展了 SyncInvoker,它具有 shorthand 方法。因此,例如,我们可以简单地调用 builder.get().

而不是调用 builder.builderGet().invoke()

所以把这些放在一起我们会得到类似

的东西
Client client = ClientBuilder.newClient();

Invocation.Builder builder = target.request();
builder = builder.header("Authorization", "Some Value");
Response response = builder.get();

或者让事情变得简单并将所有内容链接起来

Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().header(..., ...).get();