How to add Headers on RESTful call using Jersey Client API
I use the header(name, value) method and give the return to webResource var:
Client client = Client.create();
WebResource webResource = client.resource("uri");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request
appKey = "Bearer " + appKey; // appKey is unique number
//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
.header("Content-Type", "application/json;charset=UTF-8")
.header("Authorization", appKey)
.get(ClientResponse.class);
String jsonStr = response.getEntity(String.class);
Try this!
Client client = ClientBuilder.newClient();
String jsonStr = client
.target("http:....")
.request(MediaType.APPLICATION_JSON)
.header("WM_SVC.NAME", "RegistryService")
.header("WM_QOS.CORRELATION_ID", "d1f0c0d2-2cf4-497b-b630-06d609d987b0")
.get(String.class);
P.S You can add any number of headers like this!
If you want to add a header to all Jersey responses, you could also use a ContainerResponseFilter
, from Jersey's filter documentation :
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;
@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
}
}
Make sure that you initialize it correctly in your project using the @Provider
annotation or through traditional ways with web.xml
.
I think you're looking for header(name,value) method. See WebResource.header(String, Object)
Note it returns a Builder though, so you need to save the output in your webResource var.