http所有請求頭在Console中列印
阿新 • • 發佈:2018-11-08
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); } }