使用HttpServletRequest读取POST表单数据

时间:2018-07-04 12:23:15

标签: java servlets http-post jax-rs

过了几天,我试图读取内容类型为application/x-www-form-urlencoded的表单中发布的数据。

根据Mozilla docs,将通过POST请求和application/x-www-form-urlencoded内容类型发送到服务器的数据像这样发送到服务器:

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=Mom

我想用say读取密钥和toHttpServletRequest的值。

这是我的尝试:

@POST
@Path("/webhook/{psp_code}")    
public Response notifyPSP(@Context HttpServletRequest httpServletRequest,
  @PathParam("psp_code") String pspCode) {

    String payload = getRequestBody( httpServletRequest );
    Map<String, List<String>> formData = getFormData( httpServletRequest );

    log.info( "Payload {}", payload);  
    log.info( "Form Data {}", formData );
}

private String getRequestBody(HttpServletRequest request) {
    String content;

    try
    {
        ServletInputStream inputStream = request.getInputStream();
        content = IOUtils.toString( inputStream );
    }
    catch ( IOException e )
    {
        content = null;
    }
    return content;
}

private Map<String, List<String>> getFormData(HttpServletRequest request) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    Map<String, List<String>> collect = parameterMap.entrySet().stream().collect( Collectors.toMap( entry -> entry.getKey(), entry -> Arrays.asList( entry.getValue() ) ) );
    return collect;
}

输出值为空:

Payload
Form Data {}

也许我在这里遗漏了一些东西,但是我如何读取这些值?

0 个答案:

没有答案