Get HTTP header in JAX-RS

In this tutorial, we show you two ways to get HTTP request header in JAX-RS :

  • Inject directly with @HeaderParam
  • Pragmatically via @Context

1. @HeaderParam Example

In this example, it gets the browser “user-agent” from request header.

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/users")
public class UserService {

    @GET
    @Path("/get")
    public Response addUser(@HeaderParam("user-agent") String userAgent) {

        return Response.status(200)
            .entity("addUser is called, userAgent : " + userAgent)
            .build();

    }

}

Access via URI pattern “/users/get“, with FireFox, see following result :

addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0

2. @Context Example

Alternatively, you can use @Context to get “javax.ws.rs.core.HttpHeaders” directly, see equivalent version to get browser “user-agent“.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

@Path("/users")
public class UserService {

    @GET
    @Path("/get")
    public Response addUser(@Context HttpHeaders headers) {

        String userAgent = headers.getRequestHeader("user-agent").get(0);

        return Response.status(200)
            .entity("addUser is called, userAgent : " + userAgent)
            .build();

    }

}

Access via URI pattern “/users/get“, with Google Chrome, see following result :

addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 
    (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30

List all request headers

You can list all available HTTP request headers via following code :

for(String header : headers.getRequestHeaders().keySet()){
    System.out.println(header);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值