In Java, how to set the header of a Restlet Response?

Mohamed Nuur picture Mohamed Nuur · Sep 17, 2010 · Viewed 8k times · Source

I can't seem to figure out how to add headers to my restlet response. When I look at the available methods in the Response object, all I see is setStatus, setEntity, and setAttributes but none of these tell me how to set custom http headers on the response.

For example, I have a GET call the returns something like the following:

HTTP/1.1 200 OK
Content-Type: text/json
Content-Length: 123
Some-Header: the value
Some-Other-Header: another value

{
  id: 111,
  value: "some value this could be anything",
  diagnosis: {
    start: 12552255,
    end: 12552261,
    key: "ABC123E11",
    source: "S1",
  }
}

Whatever it maybe. In the handleGet method, I handle it like so:

final MediaType textJsonType = new MediaType("text/json");

@Override
public void handleGet() {
  log.debug("Handling GET...");
  final Response res = this.getResponse();

  try {
    final MyObject doc = this.getObj("hello", 1, "ABC123E11", "S1");
    final String docStr = doc.toString();

    res.setStatus(Status.SUCCESS_OK);
    res.setEntity(docStr, textJsonType);

    // need to set Some-header, and Some-other-header here!
  }
  catch(Throwable t) {
    res.setStatus(Status.SERVER_ERROR_INTERNAL);
    res.setEntity(new TextRepresentation(t.toString()));
  }
}

Answer

Bruno picture Bruno · Sep 17, 2010

Because Restlet is more about the REST architectural principles than HTTP, it tries to be protocol agnostic and doesn't expose the HTTP headers directly. However, they are stored in the org.restlet.http.headers attribute of the response (as a Form). Note that you can only set custom headers this way, not standard ones (these are handled directly by the framework, e.g. Content-Type depends on the Representation's MediaType).

See this for an example: http://blog.arc90.com/2008/09/15/custom-http-response-headers-with-restlet/ (link content also available from the Internet Archive Wayback Machine).