such as an interface, both want to implement the request parameter is Application/json, and want to implement form submission, change how to do it? Test with postman and find it impossible to get the best of both worlds.
I have a method, is not requestbody, can also implement JSON parsing, the first is to create a new wrapper class, this class can be repeated reading inputstream inside the things.
If Requestbody is added, it cannot be submitted with the form, and if you remove requestbody then you cannot get the value inside the JSON because it is all null.
Class Bodyreaderhttpservletrequestwrapper extends Httpservletrequestwrapper {Private final byte[] body; Public Bodyreaderhttpservletrequestwrapper (HttpServletRequest request) throws IOException {super (reques T);
Encoding default iso-8859-1 BODY = Streamutil.readbytes (Request.getreader (), "utf-8"); } @Override Public BufferedReader Getreader () throws IOException {return new BufferedReader (new INPUTSTREAMR Eader (getInputStream ())); } @Override Public ServletInputStream getInputStream () throws IOException {final Bytearrayinputstream Bais = New Bytearrayinputstream (body); return new ServletInputStream () {@Override public int read () throws IOException {re Turn bais.read (); } @Override public Boolean isfinished () {return false; } @Override public Boolean isReady () {return false; } @Override public void Setreadlistener (Readlistener listener) {}}; }}
And then take something from the InputStream and pull it.
public static Jsonobject Receivepost (HttpServletRequest request) throws IOException, Unsupportedencodingexception { //Read Request contents BufferedReader br = new BufferedReader (New InputStreamReader (Request.getinputstream ())); String line = null; StringBuilder sb = new StringBuilder (); while (line = Br.readline ())! = null) { sb.append (line); } Converts a JSON string to a JSON object jsonobject json=jsonobject.parseobject (sb.tostring ()); return JSON; }
Finally, the action inside the judgment is OK, done.
if (Servletrequest.getcontenttype (). Equals ("Application/json")) { servletrequest= new Bodyreaderhttpservletrequestwrapper (servletrequest); Jsonobject d= receivepost (servletrequest); } else { map<string,string[]> map= servletrequest.getparametermap (); }
Spring boot implements methods that are compatible with different request types.