当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;
}