public class HttpServletRequestHelper {
@SneakyThrows
public static HashMap<String, Object> getRequestMap(HttpServletRequest request){
HashMap<String, Object> hashMap = new HashMap<>(20);
HashMap<String, Object> map = getMap(request.getHeaderNames(), s -> request.getHeader(s.toString()));
hashMap.put("getHeaderNames", map);
Map<String, String[]> parameterMap = request.getParameterMap();
hashMap.put("parameterMap", parameterMap);
String s = StreamToString(request.getInputStream());
hashMap.put("getInputStream", s);
return hashMap;
}
/**
* 1-3:获取Map参数集合 1
*/
private static HashMap<String, Object> getMap(Enumeration<String> enumeration, Function<Object, Object> function) {
HashMap<String, Object> map = new HashMap<>(20);
while (true) {
try {
String s = enumeration.nextElement();
if (StrUtil.isBlank(s)) {
break;
}
Object apply = function.apply(s);
map.put(s, apply);
} catch (Exception ex) {
StaticLog.error(ex);
break;
}
}
return map;
}
/**
* 1-2:读取 InputStream 的内容 1
*/
private static String StreamToString(InputStream in) throws Exception {
//1、创建:字节(输入流)
ByteArrayOutputStream out =null;
try {
out = new ByteArrayOutputStream();
//2、按1024字节【缓存区】读取
int len = 0;
byte[] bt = new byte[1024];
while ((len = in.read(bt)) != -1) {
out.write(bt, 0, len);
}
//3、转换为:字符串
String content = new String(out.toByteArray());
//4、返回:字符串
return content;
}finally {
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
}
}
使用
public CommonResult<HashMap<String,Object>> xxx(HttpServletRequest request){
HashMap<String, Object> hashMap = HttpServletRequestHelper.getRequestMap(request);
StaticLog.info("xxx结束" + JSONUtil.toJsonStr(hashMap));
HashMap<String,Object> voMap=new HashMap<>(5);
return new CommonResult<>(voMap);
}