Nero丶的gravatar头像
Nero丶 2015-11-27 14:14:26

java web开发拦截器继承HandlerInterceptorAdapter如何得到请求体?

写了个拦截器继承HandlerInterceptorAdapter。。并且实现了相关方法。。我想获取到请求体,get请求的时候参数会跟在地址后面,可以直接获取到,post请求的时候,不知道怎么获取。。百度了下。。request.getParameterMap();好像获取到的也是空的。。在线等

所有回答列表(2)
最代码官方的gravatar头像
最代码官方  LV168 2015年11月27日

最近开发微信公众平台实现微信回调接口时,正好遇到了在java servlet中如何从HttpServletRequest中获取请求体的问题,不管是拦截器还是http doPost还是spring mvc的Post方法都类似

分享下相关的代码片段:

import org.apache.commons.io.IOUtils;

@RequestMapping(value = { "callback" }, method = RequestMethod.POST)
	public void callbackPost(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "signature", required = true) String signature,
			@RequestParam(value = "timestamp", required = true) String timestamp,
			@RequestParam(value = "nonce", required = true) String nonce,
			@RequestParam(value = "msg_signature", required = true) String msgSignature) {
     String encryptMsg = IOUtils.toString(request.getInputStream(), "utf-8");
}

通过IOUtils可以转换为String,也可以读取为byte[] IOUtils.toByteArray(getInputStream)

	public static void testWeixinPost() {
		try {

			HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
			// HttpHost proxy = new HttpHost("127.0.0.1", 8888);
			// httpClientBuilder.setProxy(proxy);
			CloseableHttpClient httpClient = httpClientBuilder.build();
			HttpPost httpPost = new HttpPost(
					"http://localhost/weixin/callback.htm";
			EntityBuilder b = EntityBuilder.create();
			b.setText(xml);
			HttpEntity entity = b.build();
			httpPost.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			System.out.println(EntityUtils.toString(httpResponse.getEntity()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

而在http Post的时候通过新版的HttpClient是这么调用的,注意不是和表单multipart/form-data上传文件时的http请求完全不同:

<form action="http://localhost/upload_user_activity.json" method="post"  enctype="multipart/form-data" >
    file:   <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
评论(0) 最佳答案
kwpkwp的gravatar头像
kwpkwp  LV7 2018年7月12日

怎么解决的

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友