从request 中获取body的数据

如果在controller里直接@RequestBody就可以获取,这种方式很简单,现在说下直接从request中获取。

说下场景,我是在shiro的filter中获取body中的数据:

@Override
    public boolean onAccessDenied(ServletRequest servletRequest, ServletResponse response) throws Exception{
        log.info("into onAccessDenied");
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;

            String str = httpServletRequest.getQueryString();
            BufferedReader bufferedReader = httpServletRequest.getReader();
            String bodyStr = IOUtils.read(bufferedReader);
            System.out.println("bodyStr = " + bodyStr );
            return true;
        }catch (ExpiredCredentialsException e){
            log.info("请求信息过期");
            WebUtils.toHttp(response).sendError(401,"请求信息过期,操作失败");
        }catch (Exception e){
            log.info("请求参数不合法");
            e.printStackTrace();
            WebUtils.toHttp(response).sendError(401,e.getMessage());
        }

        return false;
    }

这里给出主要的相关代码,IOUtils是dubbo的一个类,相关依赖如下:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.5.3</version>
        </dependency>

通过这种方式获取的是一个json字符串,

bodyStr =  {
    "timestamp":1523966342156
}

因为我项目中没有用到dubbo,如果为了一个body的解析引入这个感觉有些不太合适,而且启动的时候也没有正常启动,所以我把这块代码抽取了出来:

package com.test.shiro.util;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * @author Created by pangkunkun on 2018/4/20.
 * 这段代码来自dubbo
 *
 */
public class RequestBodyUtils {

    private static final int BUFFER_SIZE = 1024 * 8;

    /**
     * read string.
     *
     * @param reader Reader instance.
     * @return String.
     * @throws IOException
     */
    public static String read(Reader reader) throws IOException
    {
        StringWriter writer = new StringWriter();
        try
        {
            write(reader, writer);
            return writer.getBuffer().toString();
        }
        finally{ writer.close(); }
    }

    /**
     * write.
     *
     * @param reader Reader.
     * @param writer Writer.
     * @return count.
     * @throws IOException
     */
    public static long write(Reader reader, Writer writer) throws IOException
    {
        return write(reader, writer, BUFFER_SIZE);
    }

    /**
     * write.
     *
     * @param reader Reader.
     * @param writer Writer.
     * @param bufferSize buffer size.
     * @return count.
     * @throws IOException
     */
    public static long write(Reader reader, Writer writer, int bufferSize) throws IOException
    {
        int read;
        long total = 0;
        char[] buf = new char[BUFFER_SIZE];
        while( ( read = reader.read(buf) ) != -1 )
        {
            writer.write(buf, 0, read);
            total += read;
        }
        return total;
    }

}

如果有哪位做过shiro的正好看到这篇文章,还请告知怎么分别获取url和body中的参数,感谢。

猜你喜欢

转载自blog.csdn.net/qq_35981283/article/details/80021773