Custom response header Jersey/Java

偶尔善良 提交于 2019-12-18 01:32:08

问题


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!


回答1:


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");
    ...
}



回答2:


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



回答3:


Return a Response (a class from JAX-RS) with UserClass as the entity. On the Response you can set HTTP headers.



来源:https://stackoverflow.com/questions/17883177/custom-response-header-jersey-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!