SpringMVC獲取、重寫請求request中的json參數

如圖,postman中的json格式,後臺解析參數

我的json:{"loginName":"shanghu001","password":"shanghu1","belongType":1}

請求體解析參數的工具類:

package com.mortals.iot.framework.util;

import com.alibaba.fastjson.JSONObject;
import com.mortals.iot.module.login.web.LoginController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Description RequestUtil
 * @Author hgg
 * @Date 2020/3/6 9:44
 * @Version 1.0
 */
public class RequestUtil {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 獲取請求中參數
     * @param request
     * @return
     */
    public static JSONObject getParameters(HttpServletRequest request){
        BufferedReader bReader = null;
        InputStreamReader isr = null;
        try {
            InputStream iis = request.getInputStream();
            isr = new InputStreamReader(iis, "utf-8");
            bReader = new BufferedReader(isr);
            String str = null;
            StringBuffer buffer = new StringBuffer();

            while ((str = bReader.readLine()) != null) {
                buffer.append(str).append("\n");
            }
            logger.info(buffer.toString());
            JSONObject json = (JSONObject)JSONObject.parseObject(buffer.toString());
            logger.info("[ACCESS LOG] body args:" + (json == null ? "" : json.toJSONString()));
            return json;
        } catch (IOException e) {
        } finally{
            try {
                bReader.close();
            } catch (IOException e) {
            }
            try {
                isr.close();
            } catch (IOException e) {
            }
        }
        return new JSONObject();
    }

    /**
     * 重寫zuul路由前request的參數
     * @param ctx
     * @param reqBodyBytes
     */
    public static void rewriteRequest(RequestContext ctx, byte[] reqBodyBytes) {
        ctx.setRequest(new HttpServletRequestWrapper(ctx.getRequest()) {
            @Override
            public ServletInputStream getInputStream() {
                return new ServletInputStreamWrapper(reqBodyBytes);
            }
            @Override
            public int getContentLength() {
                return reqBodyBytes.length;
            }
            @Override
            public long getContentLengthLong() {
                return reqBodyBytes.length;
            }
        });
    }
}

獲取參數

JSONObject param = RequestUtil.getParameters(request);
loginName = param.getString("loginName");
password = param.getString("password");
belongType = param.getInteger("belongType");

重寫參數(zuul路由前pre,修改請求參數場景):

        RequestContext context = getCurrentContext();
        HttpServletRequest request = context.getRequest();


        String requestUri = context.get(FilterConstants.REQUEST_URI_KEY).toString();
        UserCookieInfo cookie = UserCookieService.getLoginCookie(request, config.getSecurityKey());

        //封裝cookie中的user信息,到request中
        JSONObject params = RequestUtil.getParameters(request);
        JSONObject user = new JSONObject();
        user.put("userId",cookie.getUser().getId());
        user.put("userName",cookie.getUser().getRealName());
        params.put("user",user);

        logger.info("用戶:"+cookie.getUser().getLoginName()+",請求:"+requestUri+";請求參數:"+params.toJSONString());

        //重寫路由前request的參數
        final byte[] reqBodyBytes = params.toJSONString().getBytes();
        RequestUtil.rewriteRequest(context, reqBodyBytes);

借鑑文章:SpringCloud Zuul修改請求參數信息

文章二:SpringCloud zuul獲取請求參數的方法(包括分離普通參數與文件流)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章