How to read response body in Jetty 12?

73 views Asked by At

I'm converting Jetty 10 code to 12 and I have a problem with reading content from org.eclipse.jetty.client.Response. I have a server (also using jetty 12) and I believe I'm filling the actual Response correctly. On the receiving side I have a AsyncContentListener. When onContent(response, chunk, callback) is called, the chunk is filled with the entire reply from the server including the headers. So I get both the body and the headers. While I can certainly parse the body out of the chunk, I don't think is how it's supposed to work. This is my parts of my server code. The ByteArrayOutputStreamis filled with the JSON content.

            Charset encoding = Request.getCharset(pRequest);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            WebServiceResponse wsr = new WebServiceResponse(new PrintStream(bout, true, encoding.name()), encoding);
            rootHandler.serve(restRequest, wsr);
            pResponse.getHeaders().put(HttpHeader.CONTENT_TYPE, wsr.getContentType());
            pResponse.setStatus(wsr.getStatus().httpStatusCode);
            bout.flush();
            pResponse.write(true, ByteBuffer.wrap(bout.toByteArray()), null);
        }

I'm happy for any pointers

1

There are 1 answers

1
mattia bonardi On

According to Jetty 12 documentation, you can read Request content using Content.Source.asStringAsync(request, UTF_8) api. I'll leave you a complete example:

@Override
public boolean handle(Request request, Response response, Callback callback) throws Exception
{
    // Non-blocking read the request content as a String.
    // Use with caution as the request content may be large.
    CompletableFuture<String> completable = Content.Source.asStringAsync(request, UTF_8);

    completable.whenComplete((requestContent, failure) ->
    {
        if (failure == null)
        {
            // Process the request content here.

            // Implicitly respond with status code 200 and no content.
            callback.succeeded();
        }
        else
        {
            // Implicitly respond with status code 500.
            callback.failed(failure);
        }
    });

    return true;
}

You can use other methods as well. You can find them here: https://eclipse.dev/jetty/documentation/jetty-12/programming-guide/index.html#pg-handler-request-content-apis