POST,Form,x-www-form-urlencoded, request.getParameter,request.getInputStream()

一段代码:

这是Filter中的一段代码,

首先通过request.getInputStream()取得请求Body的内容。

然后再通过request.getParameterMap()查询所有的请求参数信息。

HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
		
		byte[] body = StreamUtils.copyToByteArray(httpServletRequest.getInputStream()); 
		String str = new String(body);
		System.out.println(str);
		
		Map params = httpServletRequest.getParameterMap();
		System.out.println(params);

 

使用PostMan发送一个POST请求,contentType是x-www-form-urlencoded 。

包含一个请求参数,参数名称=name,参数值=hqq

发送请求,debug测试。

-- getInputStream()取得Body体,可以看到请求参数信息,已被格式化为:name=hqq

 
 

但是,通过getParameterMap()已经取不到了(至于为何,后面解释)

 

 

调整代码顺序,

先通过request.getParameterMap()查询所有的请求参数。

后通过request.getInputStream()取得请求Body的内容。

Map params = httpServletRequest.getParameterMap();
		System.out.println(params);
		
		byte[] body = StreamUtils.copyToByteArray(httpServletRequest.getInputStream()); 
		String str = new String(body);
		System.out.println(str);

 

再次发送请求,debug测试:

request.getParameterMap()能取到请求参数信息,

但是

request.getInputStream()取不着了。

 

 

 

现象说明:

根据Servlet规范,如果同时满足下列条件,则请求体(Entity)中的表单数据,将被填充到request的parameter集合中(request.getParameter系列方法可以读取相关数据): 

1 这是一个HTTP/HTTPS请求 

2 请求方法是POST(querystring无论是否POST都将被设置到parameter中) 

3 请求的类型(Content-Type头)是application/x-www-form-urlencoded 

4 request对象调用了getParameter系列方法

 

如果上述条件没有同时满足,则相关的表单数据不会被设置进request的parameter集合中,相关的数据可以通过request.getInputStream()来访问。反之,如果上述条件均满足,相关的表单数据将不能再通过request.getInputStream()来读取(原因:request.getInputStream()流只能读取一次,满足上述4个条件,将body体的内容设置进request的parameter集合中时,已经读取一次)。

 

Servlet Specifiaction 3.0: 

3.1.1 When Parameters Are Available ,The following are the conditions that mustbe met before post form data will be populated to the parameter set: 

1. The request is an HTTP or HTTPS request. 

2. The HTTP method is POST. 

3. The content type is application/x-www-form-urlencoded. 

4. The servlet has made an initial call of any of the getParameterfamily of methods on the request object. 

 

If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request object’s input stream. If the conditions are met, post form data will no longer be available for reading directly from the request object’s input stream.

 

相关文章

Postman中 form-data、x-www-form-urlencoded、raw、binary的区别

http://huangqiqing123.iteye.com/blog/2388497

解决request.getInputStream()与request.getReader()只能调用一次的问题 

http://huangqiqing123.iteye.com/blog/2237263

Java Web 修改请求参数 

http://huangqiqing123.iteye.com/blog/2229290

 

 

 

 

 

 

猜你喜欢

转载自huangqiqing123.iteye.com/blog/2396166
今日推荐