package httpHeader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestHttpHeader
*/
@WebServlet("/TestHttpHeader")
public class TestHttpHeader extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {// names.hasMoreElements()判断是否到末尾
String name = (String) names.nextElement();// 光标移到下一条
out.println("<b>" + name + "</b>" + ":" + request.getHeader(name)
+ "<br/>");// request.getHeader(name)获取表头name的值
if (name.equals("user-agent")) {
out.println("<b>" + name + "</b>" + request.getHeader(name)
+ "<br/>");
}
}
out.flush();
out.close();
}
/**
*
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response, Object Enumeration)
throws ServletException, IOException {
}
}
输出结果为:
accept:image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* //浏览器支持的格式
accept-language:zh-cn //,用于告诉服务器浏览器可以支持什么语言。如果网站支持多语种的话,可以使用这个信息来决定返回什么语言的网页
accept-encoding:gzip,
deflate //是浏览器发给服务器,声明浏览器支持的编码类型
user-agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;
Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729;
.NET4.0C; .NET4.0E) //浏览器信息
user-agentMozilla/4.0 (compatible; MSIE 7.0;
Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET
CLR 3.5.30729; .NET4.0C;
.NET4.0E)
host:127.0.0.1 //
connection:Keep-Alive //
Referer:http://www.baidu.com //从哪个页面单击进入