为什么我的PrintWriter不是由ByteArrayOutputStream写出来的?

时间:2016-07-25 21:09:57

标签: java servlets java-io outputstream bytearrayoutputstream

我有 public class test { CountDownTimer countdowntimer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { startCountDownTimer(); } void startCountDowntimer(){ countdowntimer = new CountDownTimer(10000, 1) { @Override public void onTick(long millisUntilFinished) { minText.setText(formatTimeMinutes(millisUntilFinished)); secondsText.setText(formatTimeSeconds(millisUntilFinished)); } @Override public void onFinish() { Toast.makeText(this,"Timer Finished",Toast.LENGTH_LONG).show(); } }.start(); } @Override public void onBackPressed() { super.onBackPressed(); countdowntimer.cancel(); } } 使用简单HttpServletResponseWrapper覆盖getOutputStream()。但每当我传递包装的响应时,都没有任何内容写入ByteArrayOutputStream

我做错了什么?

包装器

ByteArrayOutputStream

绕过包裹的回复

private static class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream responseBytes;

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        responseBytes = new ByteArrayOutputStream();
    }

    public byte[] getBytes() {
        return responseBytes.toByteArray();
    }

    @Override
    public ServletOutputStream getOutputStream() { return new ServletOutputStream() {
        private WriteListener writeListener;
        @Override
        public boolean isReady() { return true; }
        @Override
        public void setWriteListener(WriteListener writeListener) {
            this.writeListener = writeListener;
        }
        @Override
        public void write(int b) throws IOException {
            responseBytes.write(b);
            Optional.ofNullable(writeListener).ifPresent(WriteListener::notify);
        }
    };}

    @Override
    public PrintWriter getWriter() { return new PrintWriter(getOutputStream()); }
}

有什么想法吗?

谢谢!

0 个答案:

没有答案