Search code examples
javaweb-servicesrestjerseyjersey-client

How to pass header information as key value pair to consume rest service using jersey


I got a url of web service which returns values in json format but it needs header information in get request as key value pair e.g. I need to pass Emp_code as key and 'xyz' as value to get details of all employees in postman. Below is code which I tried

private static void getEmployees()
  {
     final Client client = new Client();
        final WebResource webResource = client.resource("http://abc/springrestexample/employees");
        final ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
        if (response.getStatus() != 200)
        {
            throw new RuntimeException("Failed Http Error code " + response.getStatus());
        }
        final String output = response.getEntity(String.class);

        System.out.println("Output from Server .... \n");
        System.out.println(output);
}

In above code how should I pass header info (key-value) to get desired result.


Solution

  • You can add .header("KEY", "Value" ) after accept.Please check below

    final Client client = new Client();
            final WebResource webResource = client.resource("http://abc/springrestexample/employees");
            final ClientResponse response = webResource.accept("application/json").header("KEY", "Value" ).get(ClientResponse.class);
            if (response.getStatus() != 200)
            {
                throw new RuntimeException("Failed Http Error code " + response.getStatus());
            }
            final String output = response.getEntity(String.class);
    
            System.out.println("Output from Server .... \n");
            System.out.println(output);