在post请求时,如果参数通过@RequestBody的json提交到后台,
后台想获取body参数体时,可以通过读流的方式获取
下面的readBodyAsString方法即为获取的json字符串
public static String readBodyAsString(HttpServletRequest request)
{
InputStream is = null;
StringBuilder sb = new StringBuilder();
try
{
is = request.getInputStream();
byte[] b = new byte[4096];
for (int n; (n = is.read(b)) != -1;)
{
sb.append(new String(b, 0, n));
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (null != is)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
如果是get请求,key-value方式,上面方法将获取不到,获取为""
网友评论