Jersey 2.x:如何在RESTful Client上添加标题 [英] Jersey 2.x: How to add Headers on RESTful Client
问题描述
我已经看过如何使用Jersey Client API在RESTful调用上添加Headers ,但这适用于Jersey 1.x.
I've already looked at How to add Headers on RESTful call using Jersey Client API, however this is for Jersey 1.x.
如何在Jersey 2.21中设置标头值(例如授权令牌)?
How do I set a header value (such as an authorization token) in Jersey 2.21?
以下是我正在使用的代码:
Here is the code I'm using:
public static String POST(final String url, final HashMap<String, String> params)
{
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(url);
String data = new Gson().toJson(params);
Entity json = Entity.entity(data, MediaType.APPLICATION_JSON_TYPE);
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
return builder.post(json, String.class);
}
推荐答案
在Jersey 2.0+,你可以注册 <$ c $的自定义实现c> ClientRequestFilter 可以操纵客户端API将发出的请求中的标题。
In Jersey 2.0+, you can register a custom implementation of ClientRequestFilter
that can manipulate the headers in the request that the Client API will send out.
您可以通过 ClientRequestContext <操作标题
传递给过滤器
方法的参数。 getHeaders()
方法返回多值地图
,你可以在上放
你的标题。
You can manipulate the headers via the ClientRequestContext
parameter that is passed into the filter
method. The getHeaders()
method returns the MultivaluedMap
on which you can put
your header(s).
你可以使用 ClientConfig
注册您的自定义 ClientRequestFilter
,然后再拨打 newClient
。
You can register your custom ClientRequestFilter
with your ClientConfig
before you call newClient
.
config.register(MyAuthTokenClientRequestFilter.class);
这篇关于Jersey 2.x:如何在RESTful Client上添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!