Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom response header Jersey/Java

I am trying to achieve the following.

Read a custom header and its value from Request:

name: username 

Now, on response, I would like to return the same header name:value pair in HTTP response.

I am using Jersey 2.0 implementation of JAX-RS webservice.

When I send the request URL Http://localhost/test/, the request headers are also passed (for the time being, though Firefox plugin - hardcoding them).

On receiving the request for that URL, the following method is invoked:

@GET @Produces(MediaType.APPLICATION_JSON) public UserClass getValues(@Context HttpHeaders header) {     MultivaluedMap<String, String> headerParams = header.getRequestHeaders();     String userKey = "name";     headerParams.get(userKey);      // ...      return user_object; } 

How may I achieve this? Any pointers would be great!

like image 920
Namenoobie Avatar asked Jul 26 '13 13:07

Namenoobie


People also ask

How do you set a response header in Java?

Setting Response Headers from Servlets The most general way to specify headers is to use the setHeader method of HttpServletResponse. This method takes two strings: the header name and the header value. As with setting status codes, you must specify headers before returning the actual document.

Can we set response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

How do I create a custom request header?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.


2 Answers

I think using javax.ws.rs.core.Response is more elegant and it is a part of Jersey. Just to extend previous answer, here is a simple example:

    @GET     @Produces({ MediaType.APPLICATION_JSON })     @Path("/values")     public Response getValues(String body) {          //Prepare your entity          Response response = Response.status(200).                 entity(yourEntity).                 header("yourHeaderName", "yourHeaderValue").build();          return response;     } 
like image 95
Alex P Avatar answered Oct 02 '22 09:10

Alex P


Just inject a @Context HttpServletResponse response as a method argument. Change the headers on that

@Produces(MediaType.APPLICATION_JSON) public UserClass getValues(@Context HttpHeaders header, @Context HttpServletResponse response) {     response.setHeader("yourheadername", "yourheadervalue");     ... } 
like image 37
Sotirios Delimanolis Avatar answered Oct 02 '22 10:10

Sotirios Delimanolis