Http Servlet request lose params from POST body after read it once

前端 未结 13 2269
一个人的身影
一个人的身影 2020-11-22 14:56

I\'m trying to accessing two http request parameters in a Java Servlet filter, nothing new here, but was surprised to find that the parameters have already been consumed! Be

13条回答
  •  猫巷女王i
    2020-11-22 15:54

    Just overwriting of getInputStream() did not work in my case. My server implementation seems to parse parameters without calling this method. I did not find any other way, but re-implement the all four getParameter* methods as well. Here is the code of getParameterMap (Apache Http Client and Google Guava library used):

    @Override
    public Map getParameterMap() {
        Iterable params = URLEncodedUtils.parse(getQueryString(), NullUtils.UTF8);
    
        try {
            String cts = getContentType();
            if (cts != null) {
                ContentType ct = ContentType.parse(cts);
                if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                    List postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), NullUtils.UTF8);
                    params = Iterables.concat(params, postParams);
                }
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        Map result = toMap(params);
        return result;
    }
    
    public static Map toMap(Iterable body) {
        Map result = new LinkedHashMap<>();
        for (NameValuePair e : body) {
            String key = e.getName();
            String value = e.getValue();
            if (result.containsKey(key)) {
                String[] newValue = ObjectArrays.concat(result.get(key), value);
                result.remove(key);
                result.put(key, newValue);
            } else {
                result.put(key, new String[] {value});
            }
        }
        return result;
    }
    

提交回复
热议问题