数据格式
请求消息数据格式为:
1.请求行
2.请求头
3.请求空行
4.请求体
示例:
GET /index.html HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
Accept: text/html,image/,/*;q=0.8
Referer: http://localhost/day14/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8
获取请求行数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getMethod(); System.out.println(method); String contextPath = request.getContextPath(); System.out.println(contextPath); String servletPath = request.getServletPath(); System.out.println(servletPath); String queryString = request.getQueryString(); System.out.println(queryString); String requestURI = request.getRequestURI(); StringBuffer requestURL = request.getRequestURL(); System.out.println(requestURI); System.out.println(requestURL); String protocol = request.getProtocol(); System.out.println(protocol); String remoteAddr = request.getRemoteAddr(); System.out.println(remoteAddr); }
|
获取请求头数据
获取请求所有头数据
1 2 3 4 5 6 7 8 9 10 11
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration<String> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()){ String name = headerNames.nextElement(); String value = request.getHeader(name); System.out.println(name+"---"+value); }
|
获取请求头数据 user-agent,实现浏览器的分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String agent = request.getHeader("user-agent"); if(agent.contains("Chrome")){ System.out.println("谷歌"); }else if(agent.contains("Firofox")){ System.out.println("火狐"); }else{ System.out.println("Edge"); } }
|
获取请求头数据 referer 实现防盗链
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String referer = request.getHeader("referer"); System.out.println(referer);
if (referer != null){ if(referer.contains("/day14")){ System.out.println("访问来源正确"); }else{ System.out.println("访问来源错误"); } } }
|
获取请求体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedReader br = request.getReader(); ServletInputStream inputStream = request.getInputStream(); String line = null; while ((line = br.readLine()) != null){ System.out.println(line); } String username = getInitParameter("username"); String password = getInitParameter("password"); System.out.println(username); System.out.println(password); }
|