在Java中,如何设置Restlet响应的头?

Moh*_*uur 4 java response restlet http-headers

我似乎无法弄清楚如何将标头添加到我的restlet响应中.当我看到在可用的方法Response的对象,我看到的是setStatus,setEntitysetAttributes但这些都不告诉我如何设置自定义HTTP头的响应.

例如,我有一个GET调用返回类似如下的内容:

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",
  }
}
Run Code Online (Sandbox Code Playgroud)

不管它是什么.在handleGet方法中,我这样处理它:

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()));
  }
}
Run Code Online (Sandbox Code Playgroud)

Bru*_*uno 10

因为Restlet更多地是关于REST架构原则而不是HTTP,它试图与协议无关,并且不直接公开HTTP头.但是,它们存储在org.restlet.http.headers响应的属性中(作为a Form).请注意,您只能设置自定义页眉这种方式,而不是标准的人(这些是直接由框架处理,如Content-Type依赖于RepresentationMediaType).

请参阅此示例:http: //blog.arc90.com/2008/09/15/custom-http-response-headers-with-restlet/(链接内容也可从Internet Archive Wayback Machine获得).