欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

has already been called for this request

程序员文章站 2024-02-03 11:21:22
...
java.lang.IllegalStateException: getReader() has already been called for this request
	at org.apache.catalina.connector.Request.getInputStream(Request.java:1056)
	at org.apache.catalina.connector.RequestFacade.getInputStream(RequestFacade.java:365)
	at javax.servlet.ServletRequestWrapper.getInputStream(ServletRequestWrapper.java:149)
	at org.springframework.http.server.ServletServerHttpRequest.getBody(ServletServerHttpRequest.java:212)
	at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver$EmptyBodyCheckingHttpInputMessage.<init>(AbstractMessageConverterMethodArgumentResolver.java:317)

HttpServletRequest的 getReader()和getInputStream()只能调用一次,Request body是流方式请求,读取一次之后,就不能再用了,看下源码:

@Override
    public BufferedReader getReader() throws IOException {

        if (usingInputStream) {
            throw new IllegalStateException(sm.getString("coyoteRequest.getReader.ise"));
        }

        // InputBuffer has no easily accessible reference chain to the Context
        // to check for a default request character encoding at the Context.
        // Therefore, if a Context default should be used, it is set explicitly
        // here. Need to do this before setting usingReader.
        if (coyoteRequest.getCharacterEncoding() == null) {
            // Nothing currently set explicitly.
            // Check the content
            Context context = getContext();
            if (context != null) {
                String enc = context.getRequestCharacterEncoding();
                if (enc != null) {
                    // Explicitly set the context default so it is visible to
                    // InputBuffer when creating the Reader.
                    setCharacterEncoding(enc);
                }
            }
        }

        usingReader = true;

        inputBuffer.checkConverter();
        if (reader == null) {
            reader = new CoyoteReader(inputBuffer);
        }
        return reader;
    }
@Override
    public ServletInputStream getInputStream() throws IOException {

        if (usingReader) {
            throw new IllegalStateException(sm.getString("coyoteRequest.getInputStream.ise"));
        }

        usingInputStream = true;
        if (inputStream == null) {
            inputStream = new CoyoteInputStream(inputBuffer);
        }
        return inputStream;

    }

可以看到Request.java调用getReader()方法后,usingReader被设置为true,getInputStream()方法会读取usingReader变量,如果为true就会报错