Skip to the content.

JAX-RS: Changing Request headers

Adding HTTP headers on server

Server code,

@Path("/hello")
public class HelloResource {
    @POST
    @Produces("text/plain")
    @Consumes("text/plain")
    public Response helloPost(String username) {
        return Response.ok("[POST] Hello "+username+" from JAX-RS on WebSphere Application server")
                       .header("myHeaderKey", "myHeaderValue")
                       .build();
    }
}

Client code,

String lsUrl = "http://localhost:9080/RSServer/HelloApp/hello";
RestClient client = new RestClient();
Resource resource = client.resource(lsUrl);
ClientResponse result = resource.contentType(MediaType.TEXT_PLAIN).post(new String("John"));
System.out.println(result.getEntity(String.class));
System.out.println(result.getHeaders().get("myHeaderKey"));

Output:

[POST] Hello John from JAX-RS on WebSphere Application server [myHeaderValue]

Adding HTTP headers on client

Server code,

@Path("/hello")
public class HelloResource {
    @POST
    @Produces("text/plain")
    @Consumes("text/plain")
    public String helloPost(String username,  @Context HttpHeaders headers) {
     System.out.println(headers.getRequestHeader("myHeaderKey"));
  //use this to get both headers and cookies
  //MultivaluedMap headerParams = hh.getRequestHeaders();
        //Map pathParams = hh.getCookies();
        return "[POST] Hello "+username+" from JAX-RS on WebSphere Application server";
    }
}

Client code,

String lsUrl = "http://localhost:9080/RSServer/HelloApp/hello";
RestClient client = new RestClient();
Resource resource = client.resource(lsUrl);
ClientResponse result = resource.contentType(MediaType.TEXT_PLAIN).header("myHeaderKey", "myHeaderValue").post(new String("John"));
System.out.println(result.getEntity(String.class));

Output:

[myHeaderValue] [POST] Hello John from JAX-RS on WebSphere Application server