总结了几种处理http Header 的方法:
利用 HttpServletRequest
import javax.servlet.http.HttpServletRequest; //... private HttpServletRequest request; //get request headers private MapgetHeadersInfo() { Mapmap = new HashMap(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
一个典型的例子如下:
"headers" : { "Host" : "yihaomen.com", "Accept-Encoding" : "gzip,deflate", "X-Forwarded-For" : "66.249.x.x", "X-Forwarded-Proto" : "http", "User-Agent" : "Mozilla/5.0 (compatible; Googlebot/2.1; + http://www.google.com/bot.html )", "X-Request-Start" : "1389158003923", "Accept" : "*/*", "Connection" : "close", "X-Forwarded-Port" : "80", "From" : "googlebot(at)googlebot.com" }
获取 user-agent
import javax.servlet.http.HttpServletRequest; //... private HttpServletRequest request; private String getUserAgent() { return request.getHeader("user-agent"); }
一个典型的例子如下:
Mozilla/5.0 (compatible; Googlebot/2.1; + http://www.google.com/bot.html )
利用 spring mvc 获取 HttpRequest Header 的例子
import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/site") public class SiteController { @Autowired private HttpServletRequest request; @RequestMapping(value = "/{input:.+}", method = RequestMethod.GET) public ModelAndView getDomain(@PathVariable("input") String input) { ModelAndView modelandView = new ModelAndView("result"); modelandView.addObject("user-agent", getUserAgent()); modelandView.addObject("headers", getHeadersInfo()); return modelandView; } //get user agent private String getUserAgent() { return request.getHeader("user-agent"); } //get request headers private MapgetHeadersInfo() { Mapmap = new HashMap(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
也许有人会说,Http Header 是可以模拟的,那么自己可以构造一个用来欺骗这些系统, 是的,的确是这样,所以在用Http Header 来传值得时候,一定要记得,所有的请求都必须经过 portal 来处理,然后 forward 到各子系统,就不会出现这个问题了。因为portal 首先拦截用户发起的所有的请求,如果是构造的用户,在portal 的sessiion 也是没有记录的,仍然会跳转到登录页面,如果在protal 的session 中记录,而且 Http Header 中也有记录,那么在子系统就是合法的用户,然后自己可以根据一些要求处理业务逻辑了
JSP/Java获取HTTP header信息(request)例子