过了几天,我试图读取内容类型为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
读取密钥和to
和HttpServletRequest
的值。
这是我的尝试:
@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 {}
也许我在这里遗漏了一些东西,但是我如何读取这些值?