在Spring HTTPMessageConverter中获取HTTP请求参数

时间:2016-04-12 09:43:37

标签: spring spring-mvc converter http-request-parameters

我正在使用Spring的AbstractHttpMessageConverter来允许我实例化我自己的对象。

转换器

    public class PaypalIPNHttpMessageConverter extends AbstractHttpMessageConverter<IPNMessage> {

    public PaypalIPNHttpMessageConverter() {
        super(MediaType.APPLICATION_FORM_URLENCODED, MediaType.TEXT_PLAIN);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz == IPNMessage.class;
    }

    @Override
    protected IPNMessage readInternal(Class<? extends IPNMessage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        //Converts HTTPRequest into map<string,string> that IPNMessage can then parse
        String requestString = IOUtils.toString(inputMessage.getBody(), "UTF-8");
        Map<String, String[]> requestMap = new LinkedHashMap<>();
        for (String keyValue : requestString.split("&")) { //each key value is delimited by &
            String[] pairs = keyValue.split("=", 2); // = pairs a key to a value
            requestMap.put(pairs[0], pairs[1].split(",")); // , splits multiple values for that key
        }
        return new IPNMessage(requestMap);
    }

    @Override
    protected void writeInternal(IPNMessage ipnMessage, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    }
}

在readINternal()中,我传递了一个HttpInputMessage对象,该对象只有getBody()函数,该函数生成HTTPRequest的InputStream。

我试图编写自己的代码来解析和构建一个ParameterMap,但如果urlencoding不同,它并不总是有效。

无论如何,我可以从转换器中获取Spring的 WebRequest HttpServletRequest 对象,并使用精彩的getParameterMap()函数吗?

TL; DR

无论如何在MessageConverter中使用WebRequest或HTTPServletRequest而不是HttpInput,所以我可以使用精彩的getParameterMap()函数,而不是重新发明轮子?

由于

2 个答案:

答案 0 :(得分:2)

看看它是如何在Spring FormHttpMessageConverter中实现的。它使用&amp;标记化请求参数。就像你的解决方案。但是,如果提供,它将从Content-Type请求标头中删除要使用的字符集。否则它使用默认的UTF-8

//extract from FormHttpMessageConverter
public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz,
            HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

        MediaType contentType = inputMessage.getHeaders().getContentType();
        Charset charset = (contentType.getCharSet() != null ? contentType.getCharSet() : this.charset);
        String body = StreamUtils.copyToString(inputMessage.getBody(), charset);

        String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
        MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);
        for (String pair : pairs) {
            int idx = pair.indexOf('=');
            if (idx == -1) {
                result.add(URLDecoder.decode(pair, charset.name()), null);
            }
            else {
                String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
                String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
                result.add(name, value);
            }
        }
        return result;
    }

答案 1 :(得分:0)

您可以使用以下代码简单地获取当前请求

HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();