Krzysztof Chris Mejka
Krzysztof Chris Mejka

Reputation: 534

Read body of a request sent to a dropwizard service

I need to read the contents of the json request sent to a dropwizard service. The message itself is serialized by dropwizard to the annotated obbject which is the input of the method (PaymentMessage object). I have added the HttpServletRequest as an input parameter of the method. The HttpServletRequest is not null, but the method HttpServletRequest#getInputStream() returns a non-null yet empty stream.

The 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"}'

The code:

@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();
}

Upvotes: 6

Views: 7719

Answers (1)

Natan
Natan

Reputation: 2858

You can change PaymentMessage paymentMessage parameter to String paymentMessage which should be the json string. Then there won't be any validation though nor you'll have the POJO directly.

Upvotes: 6

Related Questions