最近开发项目,因为有第三方调用我们的接口,我们使用SpringBoot以JavaBean的方式接收了我们预期的参数,参数接收也没有什么异常。但是有一些需求问题需要沟通,需要拿到合作第三方传入的所有参数,来进行参数核验。
如何拿到请求的所有参数呢?正常的思路肯定是从request中获取,如果是GET请求,参数在请求路径中拼接;如果是POST请求,参数在request的请求体(body)中。
一番检索,很容易拿到相关代码。但是经过实操,发现并不能如期获取到参数。经过思考,我的接口是POST请求,参数形式是json格式(使用了@RequestBody来修饰参数)。
具体过程参看如下分析
方法一
Enumeration |
|
while (parameterNames.hasMoreElements()) { |
|
String paraName = parameterNames.nextElement(); |
|
System.out.println(paraName + ": " + request.getParameter(paraName)); |
|
} |
方法二
Map |
|
Set |
|
for (Iterator |
|
Map.Entry |
|
Object ok = me.getKey(); |
|
Object ov = me.getValue(); |
|
String[] value = new String[1]; |
|
if (ov != null) { |
|
value = (String[]) ov; |
|
} else { |
|
value[0] = ov.toString(); |
|
} |
|
for (int k = 0; k < value.length; k++) { |
|
System.out.println(ok + "=" + value[k]); |
|
} |
|
} |
经过测试以上两个方法可以获取GET请求的参数,以及参数格式为form-data、x-www-form-urlencoded的POST请求,但是json格式参数(postman中为raw)的参数不能获得。
根据代码的简介程度,选择方法一,明显更舒服一些。
以上结论经过postman实测.
以上方法已经可以获取大多数情况下的请求的参数,但是明显还不能满足需求,需要获取传入json格式的参数。
经过一番检索,网上推荐的方法一般都是使用流来进行参数读取,即使用getInputStream()和getReader():
Map |
|
BufferedReader br = null; |
|
try { |
|
try { |
|
br = request.getReader(); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
String str; |
|
StringBuilder wholeStr = new StringBuilder(); |
|
while ((str = Objects.requireNonNull(br).readLine()) != null) { |
|
wholeStr.append(str); |
|
} |
|
if (StrUtil.isNotEmpty(wholeStr.toString())) { |
|
params = JSON.parseObject(wholeStr.toString(), Map.class); |
|
} |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
System.out.println(params); |
遇到的问题及解决思路
问题1 流不能多次被调用
但是又会遇到如下问题:
ERROR m.e.handler.GlobalExceptionHandler - getInputStream() has already been called for this request
java.lang.IllegalStateException: getInputStream() has already been called for this request
at org.apache.catalina.connector.Request.getReader(Request.java:1212)
at org.apache.catalina.connector.RequestFacade.getReader(RequestFacade.java:504)
根据报错信息分析简单来说,就是getInputStream()已经被调用了,不能再次调用。可是我看代码上,我也没调用。经过一番检索,原来@RequestBody注解配置后,默认会使用流来读取数据。
具体原因:
实测,不加@RequestBody注解,可以如期获得请求中的json参数,但是又不得不加@RequestBody注解。这样就需要新的思路
解决思路
写filter继承HttpServletRequestWrapper,缓存InputStream,覆盖getInputStream()和getReader()方法,使用ByteArrayInputStream is = new ByteArrayInputStream(body.getBytes());读取InputStream。
1.定义增强类,继承继承HttpServletRequestWrapper
将请求体中的流copy一份,覆写getInputStream()和getReader()方法供外部使用。每次调用覆写后的getInputStream()方法都是从复制出来的二进制数组中进行获取,这个二进制数组在对象存在期间一直存在,这样就实现了流的重复读取。
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { |
|
private byte[] body; |
|
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException { |
|
super(request); |
|
body = HttpHelper.getBodyString(request).getBytes(StandardCharsets.UTF_8); |
|
} |
|
@Override |
|
public BufferedReader getReader() throws IOException { |
|
return new BufferedReader(new InputStreamReader(getInputStream())); |
|
} |
|
@Override |
|
public ServletInputStream getInputStream() throws IOException { |
|
final ByteArrayInputStream bais = new ByteArrayInputStream(body); |
|
return new ServletInputStream() { |
|
@Override |
|
public int read() throws IOException { |
|
return bais.read(); |
|
} |
|
@Override |
|
public boolean isFinished() { |
|
return false; |
|
} |
|
@Override |
|
public boolean isReady() { |
|
return false; |
|
} |
|
@Override |
|
public void setReadListener(ReadListener readListener) { |
|
} |
|
}; |
|
} |
|
public void setInputStream(byte[] body) { |
|
this.body = body; |
|
} |
|
} |
2.构建过滤器
@Slf4j |
|
@WebFilter(filterName = "RequestWrapperFilter", urlPatterns = "/api/test/test2") |
|
public class RequestWrapperFilter implements Filter { |
|
@Override |
|
public void init(FilterConfig filterConfig) throws ServletException { |
|
} |
|
@Override |
|
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException |
|
, IOException { |
|
ServletRequest requestWrapper = null; |
|
if (request instanceof HttpServletRequest) { |
|
requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request); |
|
} |
|
if (null == requestWrapper) { |
|
log.error("过滤器包装request失败!将返回原来的request"); |
|
chain.doFilter(request, response); |
|
} else { |
|
log.info("过滤器包装request成功"); |
|
chain.doFilter(requestWrapper, response); |
|
} |
|
} |
|
@Override |
|
public void destroy() { |
|
} |
|
} |
注意事项:
/** |
|
* description:http辅助工具类 |
|
* |
|
* @author RenShiWei |
|
* Date: 2021/5/7 22:11 |
|
**/ |
|
public class HttpHelper { |
|
/** |
|
* description:从request获取body的json数据 |
|
* |
|
* @param request / |
|
* @return / |
|
* @author RenShiWei |
|
* Date: 2021/5/7 22:44 |
|
*/ |
|
public static String getBodyString(ServletRequest request) { |
|
StringBuilder sb = new StringBuilder(); |
|
ServletInputStream inputStream = null; |
|
BufferedReader reader = null; |
|
try { |
|
inputStream = request.getInputStream(); |
|
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); |
|
String line = ""; |
|
while ((line = reader.readLine()) != null) { |
|
sb.append(line); |
|
} |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} finally { |
|
if (inputStream != null) { |
|
try { |
|
inputStream.close(); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
if (reader != null) { |
|
try { |
|
reader.close(); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
|
return sb.toString(); |
|
} |
|
/** |
|
* description:从request获取body的json数据,并格式化成map形式 |
|
* |
|
* @param request / |
|
* @return / |
|
* @author RenShiWei |
|
* Date: 2021/5/7 22:44 |
|
*/ |
|
@SuppressWarnings("all") |
|
public static Map |
|
Map |
|
String bodyString = getBodyString(request); |
|
if (StrUtil.isNotEmpty(bodyString)) { |
|
params = JSON.parseObject(bodyString, Map.class); |
|
} |
|
return params; |
|
} |
|
} |
4.在SpringBoot启动类上添加@ServletComponentScan注解
@RestController |
|
@RequestMapping("/api/test") |
|
public class TestController { |
|
@GetMapping("/test1") |
|
@AnonymousAccess |
|
public ResponseEntity |
|
System.out.println("---GET请求 getParameterNames 入参---"); |
|
try { |
|
request.setCharacterEncoding("utf-8"); |
|
} catch (UnsupportedEncodingException e) { |
|
e.printStackTrace(); |
|
} |
|
Enumeration |
|
while (parameterNames.hasMoreElements()) { |
|
String paraName = parameterNames.nextElement(); |
|
System.out.println(paraName + ": " + request.getParameter(paraName)); |
|
} |
|
System.out.println("---GET请求 getParameterMap 入参---"); |
|
Map |
|
Set |
|
for (Iterator |
|
Map.Entry |
|
Object ok = me.getKey(); |
|
Object ov = me.getValue(); |
|
String[] value = new String[1]; |
|
if (ov != null) { |
|
value = (String[]) ov; |
|
} else { |
|
value[0] = ov.toString(); |
|
} |
|
for (int k = 0; k < value.length; k++) { |
|
System.out.println(ok + "=" + value[k]); |
|
} |
|
} |
|
return ResponseEntity.ok(null); |
|
} |
|
@PostMapping("/test2") |
|
@AnonymousAccess |
|
public ResponseEntity |
|
String body = HttpHelper.getBodyString(request); |
|
Map |
|
System.out.println("body: " + body); |
|
System.out.println("bodyMap: " + bodyMap); |
|
return ResponseEntity.ok(null); |
|
} |
|
} |
postman测试
GET请求
POST的JSON格式参数(其他方式结果与GET请求结果一致)
结果