RequestDemo3.java 文件:
package com.neu;
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 RequestDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test3(request);
}
//得到所有的消息头
private void test3(HttpServletRequest request) {
Enumeration<String> e = request.getHeaderNames();
while(e.hasMoreElements()){
String headerName = e.nextElement();//透明称
Enumeration<String> headerValues = request.getHeaders(headerName);
while(headerValues.hasMoreElements()){
System.out.println(headerName+":"+headerValues.nextElement());
}
}
}
//http协议是允许头有重复的情况,多个重名的头
private void test2(HttpServletRequest request) {
Enumeration<String> e = request.getHeaders("Accept-Encoding");//得到的头值
while(e.hasMoreElements()){
String headerValue = e.nextElement();
System.out.println(headerValue);
}
}
//得到指定请求消息头的值。如果没有该头,返回null
private void test1(HttpServletRequest request) {
String supportEncoding = request.getHeader("Accept-Encoding");
if(supportEncoding.contains("gzip")){
System.out.println("支持gzip压缩");
}else{
System.out.println("不支持gzip压缩");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
运行:http://localhost:8080/Request/servlet/RequestDemo3
结果:
- host:localhost:8080
connection:keep-alive
upgrade-insecure-requests:1
user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
accept-encoding:gzip, deflate, sdch
accept-language:zh-CN,zh;q=0.8