读取HttpServletRequest中的请求体

81 阅读1分钟

使用这种原始方法是为了防止json字符串中字段发生排序,以免对签名验签造成影响

public static String getRequestJson(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;
    }
    String charEncoding = request.getCharacterEncoding();
    if (charEncoding == null) {
        charEncoding = "UTF-8";
    }
    return new String(buffer, charEncoding);
}