Jersey 2.x: How to Add Headers on a RESTful Client

I already looked at How to add headers to a RESTful call using the Jersey client APIs , however this is for Jersey 1.x.

How to set a header value (e.g. 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); } 
+7
java rest jersey
source share
3 answers

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.

You can manipulate the headers with the ClientRequestContext parameter, which is passed to the filter method. The getHeaders() method returns a MultivaluedMap , on which you can put header.

You can register your custom ClientRequestFilter with ClientConfig before calling newClient .

 config.register(MyAuthTokenClientRequestFilter.class); 
+6
source share

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

 webTarget.request().header("authorization":"bearer jgdsady6323u326432").post(..)... 
+3
source share

To add to what Pradeep said, there are also headers (MultivaluedMap <String, Objects> under WebTarget.request (), if you have a bunch 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 original example 
0
source share

All Articles