比如一个接口,既想实现请求参数是application/json,又想实现form提交,改怎么做呢?用postman去测试,发现不可能做到两全其美。
我有一个方法,就是不用requestbody,也可以实现json解析,首先是新建一个包装类,这个类可以重复读inputstream里面的东西。
如果加了requestbody,就无法用form提交,如果去掉requestbody 那么就无法获取到json里面的值,因为全是null.
class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request);
//编码默认iso-8859-1 body = StreamUtil.readBytes(request.getReader(), "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 listener) { } }; } }
然后再从inputstream里面拿东西就OK拉
public static JSONObject receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException { // 读取请求内容 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } //将json字符串转换为json对象 JSONObject json=JSONObject.parseObject(sb.toString()); return json; }
最后在action里面做判断就OK了,大功告成。
if(servletRequest.getContentType().equals("application/json")) { servletRequest= new BodyReaderHttpServletRequestWrapper( servletRequest); JSONObject d= receivePost(servletRequest); } else { Map<String,String[]> map= servletRequest.getParameterMap(); }