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

从request中获取json数据的方法

程序员文章站 2022-07-17 11:04:21
从request中获取json数据的方法 package com.newpp.core.interceptor; import java.io.bufferedreader; impor...

从request中获取json数据的方法

package com.newpp.core.interceptor;

import java.io.bufferedreader;
import java.io.bytearrayinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;

import javax.servlet.servletinputstream;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletrequestwrapper;

/**
 * myrequestwrapper.
 * 
 * @author iechenyb
 */
public class myrequestwrapper extends httpservletrequestwrapper {
    private final string body;

    public myrequestwrapper(httpservletrequest request) throws ioexception {
        super(request);
        stringbuilder stringbuilder = new stringbuilder();
        bufferedreader bufferedreader = null;
        try {
            inputstream inputstream = request.getinputstream();
            if (inputstream != null) {
                bufferedreader = new bufferedreader(new inputstreamreader(inputstream));
                char[] charbuffer = new char[128];
                int bytesread = -1;
                while ((bytesread = bufferedreader.read(charbuffer)) > 0) {
                    stringbuilder.append(charbuffer, 0, bytesread);
                }
            } else {
                stringbuilder.append("");
            }
        } catch (ioexception ex) {
            throw ex;
        } finally {
            if (bufferedreader != null) {
                try {
                    bufferedreader.close();
                } catch (ioexception ex) {
                    throw ex;
                }
            }
        }
        body = stringbuilder.tostring();
    }

    @override
    public servletinputstream getinputstream() throws ioexception {
        final bytearrayinputstream bytearrayinputstream = new bytearrayinputstream(body.getbytes());
        servletinputstream servletinputstream = new servletinputstream() {
            public int read() throws ioexception {
                return bytearrayinputstream.read();
            }
        };
        return servletinputstream;
    }

    @override
    public bufferedreader getreader() throws ioexception {
        return new bufferedreader(new inputstreamreader(this.getinputstream()));
    }

    public string getbody() {
        return this.body;
    }
}