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

扶醉桌前 提交于 2019-12-04 18:12:13

问题


I've already looked at How to add Headers on RESTful call using Jersey Client API, however this is for Jersey 1.x.

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);
}

回答1:


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.

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).

You can register your custom ClientRequestFilter with your ClientConfig before you call newClient.

config.register(MyAuthTokenClientRequestFilter.class);



回答2:


If you want to add only few headers in Jersey 2.x client, you can simply add it when request is sending as follows.

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



回答3:


To add to what Pradeep said, there's also headers(MultivaluedMap < String, Objects> under WebTarget.request() if you have a gaggle of headers:

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


来源:https://stackoverflow.com/questions/32532959/jersey-2-x-how-to-add-headers-on-restful-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!