1

我正在尝试使用 restlet 创建一个 HEAD 响应。不幸的是只有一个@Get注释,但restlet作者声明,你必须使用a @Get,然后比较方法。正如文档/规范所说,不能有正文,而只有一个消息头。

现在如何创建将发送到服务器的消息头,因为以下代码不起作用,它发送此头:HTTP/1.1 204 No Content, Content-Length: 0

protected void addResponseHeader(String name, String value) {
    Form responseHeaders = (Form)getResponse().getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
    if (responseHeaders == null) {
        responseHeaders = new Form();
        getResponse().getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
    }
    responseHeaders.add(new Parameter(name, value));
}

服务器端的具体代码:

@Get
public void execute() {
    if (Method.HEAD.equals(getMethod())) {
        //optional: getResponse().getEntity().setMediaType(MediaType.TEXT_PLAIN);
        getResponse().setStatus(Status.SUCCESS_OK, "hello head");
        addResponseHeader("X-my-header", "value");
    }
}

客户端代码:

@Test
public void head() {
    Request request = new Request(Method.HEAD, url);
    Response response = query(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    Form form = (Form)response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
    assertEquals("value", form.getFirstValue("X-my-value")); // does fail because it is null
}
4

1 回答 1

2

You just need to implement @Get for real : should work with a HTTP GET fine first. Then if you issue a HTTP HEAD, it will be handled automatically by the framework, nothing else to do on your side. Just focus on getting GET implemented correctly.

于 2011-06-11T09:44:04.137 回答