Vihaan Verma
Vihaan Verma

Reputation: 13143

java httprequest getting the body from the request

I receive a post request from client. This request contains some json data which I want to part on the server side. I have created the server using httpcore. HttpRequestHandler is used for handling the request. Here is the code I thought would work

    HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();

                    InputStream inputStream = entity.getContent();

                    String str = inputStream.toString();

                    System.out.println("Post contents: " + str);*/

But I cant seem to find a way to get the body of the request using the HttpRequest object. How can I extract the body from the request object ? Thanks

Upvotes: 7

Views: 13431

Answers (2)

Pavel Netesa
Pavel Netesa

Reputation: 2102

... and for MultipartEntity use this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        entity.writeTo(baos);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String text = new String(baos.toByteArray());

Upvotes: 1

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

You should use EntityUtils and it's toString method:

String str = EntityUtils.toString(entity);

getContent returnes stream and you need to read all data from it manually using e.g. BufferedReader. But EntityUtils does it for you.
You can't use toString on stream, because it returns string representation of the object itself not it's data.
One more thing: AFAIK GET requests can't contain body so it seems you get POST request from client.

Upvotes: 7

Related Questions