通过Java获得浏览器的所有请求内容

package cn.yanliang.servlet;


import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class RequestDemo1
 */
public class RequestDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;


    public RequestDemo1() {
        // TODO Auto-generated constructor stub
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获得请求行
// 1、获取请求方式
System.out.println("请求方式:" + request.getMethod());
// 2、获得请求URI
System.out.println("URI : " + request.getRequestURI());
System.out.println("URL : " + request.getRequestURL());
// 3、获得请求协议
System.out.println("请求协议 : " + request.getProtocol());
System.out.println("---------------------------------------------");

// 获得请求头
// 1、获得指定名字的请求头内容
System.out.println("HOST : " + request.getHeader("Host"));
// 2、获得所有的请求头内容
Enumeration enums = request.getHeaderNames();
while(enums.hasMoreElements()){
String headName = enums.nextElement();
System.out.println(headName + ":" + request.getHeader(headName));
}
System.out.println("---------------------------------------------");

}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
// 获得实体内容
InputStream in = request.getInputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len = in.read(buf)) != -1){
String str = new String(buf, 0, len);
System.out.println(str);
}
}

}

你可能感兴趣的:(笔记类)