[spring boot] Get json string from request in custom interceptor

For such a requirement, you need to obtain the data in the request in a custom interceptor, and what you want to obtain is a JSON string

Then you need to write such a method in the interceptor

public static String getOpenApiRequestData(HttpServletRequest request){
        try {

            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);

        } catch (Exception e) {
            e.printStackTrace ();
        }

        return null;
    }
View Code

Then in the preHandle method of the interceptor, the call will get the String string, and then serialize it with JSON

JSONObject jsonObject1 = JSON.parseObject(OpenApiInterceptor.getOpenApiRequestData(httpServletRequest));

to get it!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326075793&siteId=291194637