【Exception】java.lang.IllegalStateException: getWriter() has already been called for this response

案发现场

2019-07-13 01:50:37.835 [ERROR][http-nio-8080-exec-3]:o.a.c.c.C.[.[localhost].[/].[dispatcherServlet] [log:175] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: getWriter() has already been called for this response] with root cause
java.lang.IllegalStateException: getWriter() has already been called for this response
	at org.apache.catalina.connector.Response.getOutputStream(Response.java:548)
	at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:210)
	at org.springframework.http.server.ServletServerHttpResponse.getBody(ServletServerHttpResponse.java:83)
protected boolean sendChallenge(ServletResponse response, int code, String msg) {
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setContentType("application/json;charset=UTF-8");
        try (
            PrintWriter printWriter = httpResponse.getWriter()
        ) {
            msg = StringUtils.isEmpty(msg) ? "" : msg;
            RestResponse restResponse = RestResponse.builder()
                                                    .code(code)
                                                    .msg(msg)
                                                    .build();
            printWriter.write(restResponse.toString());
        } catch (IOException e) {
            log.error("sendChallenge error,can not resolve httpServletResponse");
        }
        return false;
    }

解决方案

在调用用httpResponsegetWriter()会时报错 getWriter() has already been called for this response

采用getOutputStream()代替getWriter()这样就可以避免这个问题

备注:这个问题不是常有,有的spring boot版本有这个问题,这样可以用getOutputStream()

你可能感兴趣的:(Exception)