zoukankan      html  css  js  c++  java
  • 解决流不能重复使用



    在InputStream读取的时候,会有一个pos指针,他指示每次读取之后下一次要读取的起始位置,当读到最后一个字符的时候,pos指针不会重置。” 
    ,就是说InputStream的读取是单向的。但是并不是所有的InputStream实现类都是这样的实现方式。
    可以换存到byte数组。


    public
    class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8")); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } }; } } HttpHelper.java /** * 获取请求Body * * @param request * @return */ public static String getBodyString(ServletRequest request) { StringBuilder sb = new StringBuilder(); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = request.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } Filter.Java @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 防止流读取一次后就没有了, 所以需要将流继续写出去 ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request); String json = HttpHelper.getBodyString(requestWrapper); System.out.println(json); filterChain.doFilter(requestWrapper, response);
  • 相关阅读:
    python 变量作用域
    python 函数与模块
    python 程序控制结构
    python zip() map() filter()
    python 迭代和列表解析
    python 字典视图
    Matlab程序设计
    Matlab 基本绘图练习 包含极坐标
    Matlab 软件绘图
    Pandas 控制输出格式和精度
  • 原文地址:https://www.cnblogs.com/zyzcj/p/7265087.html
Copyright © 2011-2022 走看看