Raffo
Raffo

Reputation: 1652

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?

Upvotes: 8

Views: 16641

Answers (1)

Pritam Barhate
Pritam Barhate

Reputation: 775

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();

Upvotes: 5

Related Questions