又這樣的需求,需要在自定義的攔截器中獲取request中的數據,想獲取到的是JSON字符串
那需要在攔截器中寫這樣一個方法
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; }
然后在攔截器的preHandle方法中,調用就拿到了String字符串,然后自己JSON序列化一下
JSONObject jsonObject1 = JSON.parseObject(OpenApiInterceptor.getOpenApiRequestData(httpServletRequest));
即可得到!
