java get request parameters in request

1. get and post request methods

(1) request.getParameterNames(); after all parameter keys are obtained. Traverse request.getParameter(key) to get value

 (2)request.getParameterMap() . The parameter key and value are included directly, which is simple and convenient


Map<String, String[]>maps =  request.getParameterMap();

for (Map.Entry<String, String[]> entry : maps.entrySet()) { String cs = entry.getKey() + ":"+Arrays.toString(entry.getValue())+";"; }


2. The request type is request payload

The file flow is not introduced here, mainly for requests with @ RequestBody mode on the back end

This kind of data cannot be obtained through the above two methods. It is stored in the stream and needs to be obtained through getInputStream() or getReader()

public String getRequestData(HttpServletRequest httpServletRequest){
        HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(httpServletRequest);
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        InputStreamReader inputStreamReader=null;
        ServletInputStream servletInputStream =null;
        try {
            servletInputStream =  httpServletRequestWrapper.getInputStream();
            inputStreamReader=new InputStreamReader (servletInputStream, Charset.forName("UTF-8"));
            reader = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = reader.readLine()) != null) {
        } catch (IOException e) {
            return "";
        }finally {
            try {
            } catch (IOException e) {
        return sb.toString ();

It should be noted that getInputStream() can only be used once to get the stream. If it is called multiple times, it needs to be cached, otherwise the data of the stream will not reach the Controller layer and a 400 error will be reported

Keywords: Java

Added by thebadbad on Tue, 05 Nov 2019 23:43:23 +0200