1.目标:将http中的请求头全部打印在Console中
2.基本语句
//1.获得指定的头
String header = response.getHeader("User-Agert");
System.out.println(header); //2.获得所有头的名称
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {//判断是否还有下一个元素
String nextElement = headerNames.nextElement();//获取headerNames集合中的请求头
String header2 = request.getHeader(nextElement);//通过请求头得到请求内容
System.out.println(nextElement+":"+header2);
3.运行结果
4.完整代码
package com.hdh.requesd; import java.io.IOException;
import java.util.Enumeration; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class requestHead extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.获得指定的头
String header = response.getHeader("User-Agert");
System.out.println(header); // 2.获得所有头的名称
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {// 判断是否还有下一个元素
String nextElement = headerNames.nextElement();// 获取headerNames集合中的请求头
String header2 = request.getHeader(nextElement);// 通过请求头得到请求内容
System.out.println(nextElement + ":" + header2); } } protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }