SpringMVC接收Postman post json数据
当postman向服务端post数据时,一般要求在body里已x-www-form-urlencoded格式写成key-value的形式。服务端通过以下代码可以取到参数
final Map<String, String> allParams = Maps.newHashMap();
final Enumeration<String> paramEnum = request.getParameterNames();
while (paramEnum.hasMoreElements()) {
String parameterName = paramEnum.nextElement();
allParams.put(parameterName, request.getParameter(parameterName));
}
但是当post向服务端post raw格式数据时,以上方式就取不到参数列表了。此时用以下方式取参数
String postString = getRequestPostString(request);
if (!StringUtil.isEmpty(postString)){
JSONObject jsonObject = JSON.parseObject(postString);
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof JSONArray) {
allParams.put(key, JSON.toJSONString(value));
} else {
allParams.put(key, String.valueOf(value));
}
}
}
private String getRequestPostString(HttpServletRequest request) throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = Charset.defaultCharset().name();
}
return new String(buffer, charEncoding);
}
private byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
/*当无请求参数时,request.getContentLength()返回-1 */
if (contentLength < 0) {
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i, contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
![](https://img2020.cnblogs.com/blog/479975/202108/479975-20210812223620577-372116739.jpg)
积跬步以致千里,积小流以成江海。
2016年5月之前的博文发布于51cto,链接地址:shamrock.blog.51cto.com
2016年5月之后博文发布与cnblogs上。
Github地址 https://github.com/umgsai
Keep moving~!!!
2016年5月之前的博文发布于51cto,链接地址:shamrock.blog.51cto.com
2016年5月之后博文发布与cnblogs上。
Github地址 https://github.com/umgsai
Keep moving~!!!