Atrix1987 Atrix1987 - 5 months ago 28
Java Question

Restlet Getting HTTP Status code 204 instead of 200

For the 1st request, I get the JSON response. From the next request onwards I start getting this log and HTTP Status Code 204, even though the ServerResource is successfully returning a representation

org.restlet.engine.adapter.ServerAdapter commit
WARNING: A response with an unavailable and potentially non empty entity was returned. Ignoring the entity for resource http://localhost:8888/xyz?abc=def


Application class for wiring routes

@Override
public Restlet createInboundRoot() {
router = new Router(getContext());
CorsService corsService = new CorsService();
corsService.setAllowedOrigins( new HashSet<String>(Arrays.asList("http://example.com")));
corsService.setAllowedCredentials(true);
getServices().add(corsService);
router.attach("/xyz", XYZ.class);
}


Server Resource which handles and returns a JSON Representation

public class XYZ extends ServerResource {

private static final Logger logger = Logger.getLogger("API:XyZ");

@Get(":json")
public Representation handleGetRequest() {
..
return API_RESPONSE_JSON_REPRESENTATION_SUCCESS;
}
}

Answer

After releasing the response, the representation state available is set to false. So subsequent calls to the ServerResource, returns the Representation but in handle() method it is set to 204 since getResponseEntity().isAvailable() returns false.

From ServerResource:

@Override
public Representation handle() {
       ...
        } finally {
            if (Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.equals(getStatus())) {
                updateAllowedMethods();
            } else if (Status.SUCCESS_OK.equals(getStatus())
                    && (getResponseEntity() == null || !getResponseEntity()
                            .isAvailable())) {
                getLogger()
                        .fine("A response with a 200 (Ok) status should have an entity. "
                                + "Changing the status to 204 (No content).");
                setStatus(Status.SUCCESS_NO_CONTENT);
            }
        }
    }
    return result;
}

SOLUTION

Either return a new representation every time or setAvailable to true before returning the representation