Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access HTTP request's body with RESTEasy

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?

like image 772
Raffo Avatar asked Sep 27 '12 09:09

Raffo


1 Answers

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();
like image 77
Pritam Barhate Avatar answered Sep 28 '22 04:09

Pritam Barhate