How to add Headers on RESTful call using Jersey Client API

181,113

Solution 1

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.

Solution 2

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

Solution 3

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!

Solution 4

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.

Solution 5

String sBodys="Body";
HashMap<String,String> headers= new HashMap<>();
Client c = Client.create();
WebResource resource = c.resource("http://consulta/rs");
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
if(headers!=null){
      LOGGER.debug("se setean los headers");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          LOGGER.debug("key: "+entry.getKey());
          LOGGER.debug("value: "+entry.getValue());
          builder.header(key, value);
      }
  }
ClientResponse response = builder.post(ClientResponse.class,sBodys);
Share:
181,113
Eric
Author by

Eric

Updated on May 19, 2020

Comments

  • Eric
    Eric almost 4 years

    Here is the Format for RESTful call:

    HEADERS:
        Content-Type: application/json;charset=UTF-8
        Authorization: Bearer Rc7JE8P7XUgSCPogjhdsVLMfITqQQrjg
    
    REQUEST:
        GET https://api.example.com/1/realTime?json={"selection":{"includeAlerts":"true","selectionType":"registered","selectionMatch":"","isTheEvent":"true","includeRuntime":"true"}}
    

    Here is my codes:

                    try
                    {
                     Client client = Client.create();
                     WebResource webResource = 
                             client.resource("https://api.example.com/1/realTime?json=
                             {"selection":{"includeAlerts":"true","selectionType":"registered","selectionMatch":"","isTheEvent":"true","includeRuntime":"true"}}");
    
                     //add header:Content-Type: application/json;charset=UTF-8
                     webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
    
                     //add header: Authorization Bearer Rc7JE8P7XUgSCPogsdfdLMfITqQQrjg
                     value = "Bearer " + value;
                     webResource.setProperty("Authorization", value);
    
                     MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
                     queryParams.add("json", js);
    
                     //Get response from RESTful Server
                     jsonStr = webResource.get(String.class);
                     System.out.println("Testing:");
                     System.out.println(jsonStr);
    
                    }
                    catch (Exception e)
                    {
                      System.out.println (e.getMessage());
                      e.printStackTrace();
                      System.exit(0);
                    }
    

    But it returns error

    com.sun.jersey.api.client.UniformInterfaceException: GET https://api.example.com/1/realTime? returned a response status of 500
        at com.sun.jersey.api.client.WebResource.handle(WebResource.java:607)
        at com.sun.jersey.api.client.WebResource.get(WebResource.java:187)
        at net.yorkland.restful.GetThermostatlist.GetThermostats(GetThermostatlist.java:60)
    

    I think I didn't add headers correctly.

    Can someone help me to fix it? Please give me advice how to add headers on request.

    Thank you

  • Eric
    Eric over 10 years
    Hi The Architect, Thank you for your solution. I did it, but the result is not my expected. Could I set parameters and headers at the same time. Please see my following post.
  • eLRuLL
    eLRuLL over 10 years
    I saw that on your question you were creating a String for your "appKey", that was correct? appKey = "Bearer " + something ??
  • Eric
    Eric over 10 years
    Hi eLRuLL, if we give a name to "Bearer appKey", it should be better for using authorizationStr. However, in order to reduce the using memory for creating new variable. I use appKey="bearer" + appKey. Please let's me know if you have any questions.
  • SuperCow
    SuperCow about 7 years
    Is there a way to add a dynamic amount of headers?
  • 500 Server error
    500 Server error over 6 years
    worked for me! the provider annotation @Provider did the trick
  • Dan Ortega
    Dan Ortega about 5 years
    Thank you so much. This is the very right response. I appreciate it.
  • Wheezil
    Wheezil over 3 years
    Thanks, this is what I was looking for. We are creating proxies with WebResourceFactory.newResource(), and this looks like the way to do it.
  • S.P Singh
    S.P Singh over 3 years
    While using the solution, it is important to use the same import statement, otherwise, you can make mistake in using the snippet. Thanks for the solution.