读取发送到Dropwizard服务的请求主体

6
我需要读取发送到Dropwizard服务的JSON请求内容。消息本身由Dropwizard序列化为带注释的对象,该对象是方法(PaymentMessage对象)的输入。我已将HttpServletRequest添加为方法的输入参数。 HttpServletRequest不为空,但方法HttpServletRequest#getInputStream()返回一个非空但流。
curl命令: curl -i -X POST -H'Content-Type: application/json; charset=UTF-8' \ http://localhost:8080/NL/users/555855/payments -d '{"eventId":"110099110099","hznHouseholdId":"1234567_nl","ipAddress":"123.123.123.123","transactionId":"799ef666-e09c-8350-247b-c466997714ad","transactionDate":"2014-09-29T16:56:21Z","appName":"Flappy Bird"}' 代码:
@POST
@Path("/{countryCode}/users/{customerId}/payments")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response processPaymentAction(
        @Context final HttpServletRequest request,
        @Nonnull @PathParam("countryCode") final String countryCode,
        @Nonnull @PathParam("customerId") final String customerId,
        @Valid PaymentMessage paymentMessage)
        throws IOException, ServletException {

    LOG.debug("Request "+request.toString());
    final ByteSource byteSource = new ByteSource() {
        @Override
        public InputStream openStream() throws IOException {
            return request.getInputStream();
        }
    };
    LOG.debug("charset "+request.getCharacterEncoding());
    final String contents = byteSource.asCharSource(Charset.forName(request.getCharacterEncoding())).read();
    LOG.debug("contents: "+contents);
    return Response.status(Response.Status.ACCEPTED).build();
}

帖子正文应该像你说的那样映射到PaymentMessage。您想从请求对象中获取什么,而这不是Jackson应该为您映射的POJO的一部分? - th3morg
我试图以字符串形式获取消息正文并将其序列化为POJO对象,因为:
  1. 我想使用正文来验证请求的md5摘要
  2. 我想将输入序列化为对象,因为对象更容易使用 :)
- Krzysztof Chris Mejka
1个回答

6
你可以将参数PaymentMessage paymentMessage更改为String paymentMessage,它应该是JSON字符串。这样做虽然没有任何验证,也不会直接得到POJO。

是的,最终我做的就是将字符串自己反序列化为POJO对象。 - Krzysztof Chris Mejka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接