package com.dmo.util;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* request 相关操作工具
*/
public class RequestUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);
/**
* 获取body参数
* 获取body会导致Controller获取不到RequestBody
*/
public static JSONObject getBodyParams(HttpServletRequest request){
try {
StringBuilder sb = new StringBuilder();
request.getReader().lines().forEach(sb::append);
String queryString = sb.toString();
JSONObject bodyParams = JSONObject.parseObject(queryString);
LOGGER.info("body Params: {}" + bodyParams.toJSONString());
return bodyParams;
}catch (IOException | NullPointerException e){
return null;
}
}
/**
* 获取Header参数
*/
public static JSONObject getHeaderParams(HttpServletRequest request){
Enumeration enumeration = request.getParameterNames();
JSONObject inputParam = new JSONObject();
while(enumeration.hasMoreElements()){
String name = (String) enumeration.nextElement();
inputParam.put(name, request.getParameterValues(name));
}
LOGGER.info("header Params: {}", inputParam.toJSONString());
return inputParam;
}
}