简体   繁体   English

Jersey 2.x:如何在RESTful Client上添加Headers

[英]Jersey 2.x: How to add Headers on RESTful Client

I've already looked at How to add Headers on RESTful call using Jersey Client API , however this is for Jersey 1.x. 我已经看过如何使用Jersey Client API在RESTful调用上添加Headers ,但这适用于Jersey 1.x.

How do I set a header value (such as an authorization token) in Jersey 2.21? 如何在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);
}

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. 在Jersey 2.0+中,您可以注册ClientRequestFilter的自定义实现,该实现可以操作客户端API将发出的请求中的标头

You can manipulate the headers via the ClientRequestContext parameter that is passed into the filter method. 您可以通过传递给filter方法的ClientRequestContext参数来操作标头。 The getHeaders() method returns the MultivaluedMap on which you can put your header(s). getHeaders()方法返回可以put标题的MultivaluedMap

You can register your custom ClientRequestFilter with your ClientConfig before you call newClient . 在调用newClient之前,可以使用ClientConfig 注册自定义ClientRequestFilter

config.register(MyAuthTokenClientRequestFilter.class);

如果您只想在Jersey 2.x客户端中添加少量标头,则只需在发送请求时添加它,如下所示。

webTarget.request().header("authorization":"bearer jgdsady6323u326432").post(..)...

To add to what Pradeep said, there's also headers(MultivaluedMap < String, Objects> under WebTarget.request() if you have a gaggle of headers: 要添加到Pradeep所说的内容,如果你有一堆标题,那么还有标题(WebTarget.request()下的MultivaluedMap <String,Objects>:

MultivaluedMap head = new MultivaluedHashMap();

head.add("something-custom", new Integer(10));
head.add("Content-Type", "application/json;charset=UTF-8");

builder.headers ( head ); // builder from Joshua's original example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM