我需要阅读发送到dropwizard服务的json请求的内容。消息本身由dropwizard序列化为带注释的对象,该对象是方法的输入(PaymentMessage
对象)。我已将HttpServletRequest
添加为该方法的输入参数。 HttpServletRequest
不为null,但方法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 paymentMessage
参数更改为String paymentMessage
,该参数应为json字符串。这样就不会进行任何验证,也不会直接拥有POJO。
关于java - 读取发送到Dropwizard服务的请求的正文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26317224/