读取Request body方法
一:传统方法
StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null;
try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } } catch (IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { throw ex; } } } body = stringBuilder.toString();
二:简洁方法
import org.apache.commons.io.IOUtils; String body = IOUtils.toString(request.getInputStream());
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!