servlet笔记(四)获取http请求头信息

本文详细介绍了在Servlet中如何获取HTTP请求头信息,包括通用方法如getHeader、getHeaders、getHeaderNames,以及针对特定信息如getCookies、getAuthType等。示例代码展示了获取并打印所有请求头信息的过程,特别是user-agent字段,可用于识别用户使用的浏览器类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.读取http请求头信息

使用HttpRequest中的方法

*一般方法:

getHeader

getHeaders

getHeaderNames

*专门方法:

getCookies

getAuthType

......

获得所有的请求头信息的代码:

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    	Enumeration<String> enum1 = request.getHeaderNames();
		  while(enum1.hasMoreElements()){
		  	String name = enum1.nextElement();
		  	String value = request.getHeader(name);
		  	System.out.println(name+":"+value);
		  }
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}
输出结果:

15:01:26,718 INFO  [STDOUT] accept:application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
15:01:26,718 INFO  [STDOUT] accept-language:zh-CN
15:01:26,718 INFO  [STDOUT] accept-encoding:gzip, deflate
15:01:26,719 INFO  [STDOUT] user-agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)
15:01:26,719 INFO  [STDOUT] host:localhost:8080
15:01:26,719 INFO  [STDOUT] connection:Keep-Alive
15:01:26,719 INFO  [STDOUT] cookie:JSESSIONID=657E2CE8E6964CC13943A7D227C88779

注:用不同的浏览器输出的内容不同。


2.根据user-agent来判断所使用的浏览器,代码内容如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
     //判断所使用的浏览器
     String userAgent = request.getHeader("user-agent");
     if(userAgent.indexOf("MSIE")!=-1){  	
       System.out.println("您当前使用的是IE浏览器");
     }else{  	
       System.out.println("您当前使用的是其他浏览器");
     }
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
     doGet(request,response);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值