Igor
Igor

Reputation: 866

Restlet Filter Post request

I would like to filter a Post request in Filter (prior it getting to the Resource). To filter the request I want to retrieve a token from the bode request and do some testing on it.

Current Resource:

@Post
public JsonRepresentation init(JsonRepresentation jRep) {
    String token = jRep.getJsonObject().getString("token");
    .
    .
    .
}

Current Filter:

@Override
protected int beforeHandle(Request request, Response response) {
  int result = STOP;
  String token = (String) Request.getCurrent().getAttributes().get("token");
  .
  .
  .
}

These code does not retrieve the token.

My question is how can I retrieve a body request?

Upvotes: 1

Views: 637

Answers (3)

Thierry Boileau
Thierry Boileau

Reputation: 866

As it is dangerous to store request entities directly into memory (imagine if a client send a tera-bytes representation), the framework does not persist representations into memory by default, they can only be read once (from the socket).

I guess the answers to your issue may be read from here: Restlet reuse InputStream

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202146

You can directly get the payload text of the request from its associated entity object, as described below:

Representation repr = request.getEntity();
String content = repr.getText();

Hope it helps you, Thierry

Upvotes: 2

Grigory
Grigory

Reputation: 86

you can try something like this to retreive the body :

public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    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;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}

Upvotes: 1

Related Questions