spring boot 中實現兼容不一樣的請求類型的方法。

  好比一個接口,既想實現請求參數是application/json,又想實現form提交,改怎麼作呢?用postman去測試,發現不可能作到一箭雙鵰。json

  我有一個方法,就是不用requestbody,也能夠實現json解析,首先是新建一個包裝類,這個類能夠重複讀inputstream裏面的東西。app

  若是加了requestbody,就沒法用form提交,若是去掉requestbody 那麼就沒法獲取到json裏面的值,由於全是null.ide

class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request)
            throws IOException {
        super(request);
    //編碼默認iso-8859-1 body = StreamUtil.readBytes(request.getReader(), "utf-8"); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener listener) { } }; } }

  而後再從inputstream裏面拿東西就OK拉post

public static JSONObject receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {

        // 讀取請求內容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //將json字符串轉換爲json對象
        JSONObject json=JSONObject.parseObject(sb.toString());
        return json;
    }

  最後在action裏面作判斷就OK了,大功告成。測試

if(servletRequest.getContentType().equals("application/json"))
        {
            servletRequest= new BodyReaderHttpServletRequestWrapper( servletRequest);
            JSONObject d= receivePost(servletRequest);
        }
        else
        {
           Map<String,String[]> map= servletRequest.getParameterMap();

        }
相關文章
相關標籤/搜索