简体   繁体   中英

Retrieve response body from ClientResource

I try to issue a POST request with ClientResource , I'm able to retrieve the response STATUS , I also want to get the response body when I get an exception.

Here is my code:

public static Pair<Status, JSONObject> post(String url, JSONObject body) {
    ClientResource clientResource = new ClientResource(url);
    try {
        Representation response = clientResource.post(new JsonRepresentation(body), MediaType.APPLICATION_JSON);

        String responseBody = response.getText();
        Status responseStatus = clientResource.getStatus();

        return new ImmutablePair<>(responseStatus, new JSONObject(responseBody));
    } catch (ResourceException e) {
        logger.error("failed to issue a POST request. responseStatus=" + clientResource.getStatus().toString(), e);
        //TODO - how do I get here the body of the response???
    } catch (IOException |JSONException e) {
        throw e;
    } finally {
        clientResource.release();
    }
}

Here is the code that my server resource returns in case of failure

getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
        put("result", "failed to execute") );
return response;

I try to catch the "result" with no success

In fact, the getResponseEntity method returns the content of the response. It corresponds to a representation. You can wrap it by a JsonRepresentation class if you expect some JSON content:

try {
    (...)
} catch(ResourceException ex) {
    Representation responseRepresentation
           = clientResource.getResponseEntity();
    JsonRepresentation jsonRepr
           = new JsonRepresentation(responseRepresentation);
    JSONObject errors = jsonRepr.getJsonObject();
}

You can notice that Restlet also supports annotated exceptions.

Otherwise I wrote a blog post about this subject: http://restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/ . I think that it could help you.

Thierry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM