8

I'm looking for a way to directly access the body of the HTTP request. In fact, in my code I receive different parameters in the body and I don't know in advance exactly what I will receive. Moreover I want to be as flexible as possible: I'm dealing with different requests that can vary and I want to handle them in a single method for each type of request (GET, POST, ... ). Is there a way to handle this level of flexibility with RESTEasy? Should I switch to something else?

Raffo
  • 1,642
  • 6
  • 24
  • 41
  • I tried using MessageBodyReaderInterceptor but I am not even sure that is made to do what I want. As far as I know, usually with RESTEasy you write methods that accept a POJO or several parameters, but I don't know them, so I cannot specify them... – Raffo Sep 27 '12 at 09:38

1 Answers1

5

As per the code given in this answer you can access the HTTPServletRequest Object.

Once you have HTTPServletRequest object you should be able access the request body as usual. One example can be:

String requestBody = "";
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
    InputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[128];
        int bytesRead = -1;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }
    } else {
        stringBuilder.append("");
    }
} catch (IOException ex) {
    throw ex;
} finally {
    if (bufferedReader != null) {
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            throw ex;
        }
    }
}
requestBody = stringBuilder.toString();
Community
  • 1
  • 1
Pritam Barhate
  • 765
  • 7
  • 22