Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 438
Vihaan Verma Avatar asked Sep 21 '12 15:09

Vihaan Verma


People also ask

How do I get request body from post request?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String.

How can I get request body from servlet?

Here is how it is done: InputStream requestBodyInput = request. getInputStream(); NOTE: You will have to call this method before calling any getParameter() method, because calling the getParameter() method on an HTTP POST request will cause the servlet engine to parse the HTTP request body for parameters.

How do you read request payload?

There are two methods for reading the data in the body: getReader() returns a BufferedReader that will allow you to read the body of the request. getInputStream() returns a ServletInputStream if you need to read binary data.


2 Answers

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.

like image 122
Mikita Belahlazau Avatar answered Sep 17 '22 20:09

Mikita Belahlazau


... and for MultipartEntity use this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        entity.writeTo(baos);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String text = new String(baos.toByteArray());
like image 35
Pavel Netesa Avatar answered Sep 21 '22 20:09

Pavel Netesa