在request中获取请求中的json数据

一直以来,前台提交的json数据在springmvc中都是使用@RequestBody进行接受.

以至于今天由于在springsecurity中需要获取到json数据,一时间没有了头绪.

理论上数据都应该可以在request中获取到,但是没查到,源码中也没有发现.

多次查找了一些博客或其他文章.终于找到了一篇文章完美解决了.下面是代码

package com.ycgwl.kylin.security.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;

public class GetRequestJsonUtils {
	
	public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
		String json = getRequestJsonString(request);
		return JSONObject.parseObject(json);
	}
	 /***
     * 获取 request 中 json 字符串的内容
     * 
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
        // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**      
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例:
     * </pre>
     * @param request
     * @return
     * @throws IOException      
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**      
     * 描述:获取 post 请求内容
     * <pre>
     * 举例:
     * </pre>
     * @param request
     * @return
     * @throws IOException      
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }

}

一个工具类.可以从request中获取到post提交时的json参数,下面是使用

	JSONObject json = GetRequestJsonUtils.getRequestJsonObject(request);
		String username = json.getString(usernameParameter);
		String password = json.getString(passwordParameter);
		String company = json.getString(companyParameter);

成功获取到了数据.原文章连接:

http://blog.csdn.net/tengdazhang770960436/article/details/50149061


猜你喜欢

转载自blog.csdn.net/alan_waker/article/details/79477370