从HttpServletRequest中获取body中的参数几种方式
从HttpServletRequest中如何获取body中的参数?
一、
Map<String,Object> params = new HashMap<String, Object>();
BufferedReader br;
try {
br = request.getReader();
String str, wholeParams = "";
while((str = br.readLine()) != null){
wholeParams += str;
}
if(StringUtils.isNotBlank(wholeParams)){
params = JSON.parseObject(wholeParams,Map.class);
}
} catch (IOException e) {
logger.error("",e);
}
二、servlet中获取
import com.alibaba.dubbo.common.utils.IOUtils;
public class BusinessServlet extends HttpServlet{
public static final Logger log = Logger.getLogger(BusinessServlet.class);
private static final long serialVersionUID = 1L;
private static BusinessService service;
static{
service = (BusinessService) WebContext.getBean("businessService");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
String body = IOUtils.read(reader);
String name = req.getParameter("name");
if(StringUtils.isNotBlank(body)){
log.info("business receive somthing with body :"+body);
}
res.setCharacterEncoding("UTF-8");
res.setContentType("application/json");
res.setStatus(HttpServletResponse.SC_OK);
res.getWriter().println(service.getName(name));
}
}
public class HttpServletRequestReader
{
// 字符串读取
// 方法一
public static String ReadAsChars(HttpServletRequest request)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try
{
br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (null != br)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
// 方法二
public static void ReadAsChars2(HttpServletRequest request)
{
InputStream is = null;
try
{
is = request.getInputStream();
StringBuilder sb = new StringBuilder();
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();
}
}
}
}
// 二进制读取
public static byte[] readAsBytes(HttpServletRequest request)
{
int len = request.getContentLength();
byte[] buffer = new byte[len];
ServletInputStream in = null;
try
{
in = request.getInputStream();
in.read(buffer, 0, len);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return buffer;
}
}
PS:
HttpServletRequest 请求中的 body 内容仅能调用 request.getInputStream(), request.getReader()和request.getParameter("key") 方法读取一次,重复读取会报 java.io.IOException: Stream closed 异常。