Web中通过HttpServletReqeust对象获取Body中数据

74 阅读1分钟
// 从request的输入流中获取数据字节
private byte[] getParameterByte(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;
}

// 转换成指定对象
LoginUserDTO loginUserDTO = JSON.parseObject(new String(parameterByte, StandardCharsets.UTF_8), LoginUserDTO.class);