根据大佬博客,集成的工具类:
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class HttpServletRequestUtils {
/**
* 解析HttpServletRequest参数
*
* @param request
* @return
* @throws IOException
*/
public static Map<String, Object> getRequestParams(HttpServletRequest request) throws IOException {
String method = request.getMethod();
if ("GET".equals(method)) {
return getHttpServletRequestFormParams(request);
}
if ("POST".equals(method)) {
return getHttpServletRequestJsonParams(request);
}
return new HashMap<>();
}
/**
* @param request
* @return java.util.Map<java.lang.String, java.lang.Object>
* @description: 获取 HttpServletRequest 参数 表单参数
* GET:地址栏中直接给出参数:http://localhost/param/ParamServlet?p1=v1&p2=v2;
* POST:表单
* @date: 2021/9/24
*/
public static Map<String, Object> getHttpServletRequestFormParams(HttpServletRequest request) {
Map<String, Object> paramMap = new HashMap<>();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String[] parameterValues = request.getParameterValues(paramName);
if (1 == parameterValues.length) {
String paramValue = parameterValues[0];
paramMap.put(paramName, paramValue);
}
}
return paramMap;
}
/**
* @param request
* @return java.util.Map<java.lang.String, java.lang.Object>
* @description: 解析HttpServletRequest参数 json格式
* POST:JSON格式
* @date: 2021/9/24
*/
public static Map<String, Object> getHttpServletRequestJsonParams(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
if (contentLength <= 0) {
return new HashMap<>();
}
byte[] buffer = new byte[contentLength];
for (int i = 0; i < contentLength; ) {
int readLen = request.getInputStream().read(buffer, i, contentLength - i);
if (-1 == readLen) {
break;
}
i += readLen;
}
Map<String, Object> maps = (Map<String, Object>) JSON.parse(buffer);
return maps;
}
}
最后的调用方式:
post 传json:
url:localhost:8100/xxx/yyy/sendMssage
post:
{
"companyName":"xcxxxx公司",
"telePhone":"11111111",
"msgContext":"内容111test 1"
}
get 请求:
localhost:8100/xxx/yyy/sendMssage?companyName=xxx分公司&telePhone=2222222&msgContext=内容fff test 1
参考博客:
get和表单post方式:
Springboot 定义接口方法同时支持GET和POST请求_真空零点能的博客-优快云博客
post 的json解析:
本文介绍了一个实用的工具类,用于解析HTTP请求中的参数,包括GET和POST请求,并支持JSON格式的数据解析。该工具类可以方便地从HttpServletRequest中提取参数。
900

被折叠的 条评论
为什么被折叠?



