开发者

How to construct message header for a HEAD response with restlet

开发者 https://www.devze.com 2023-03-12 11:36 出处:网络
I\'m trying to create a HEAD response with restlet. Unfortunatly there is ony a @Get annotation, but the restlet author states, that you have to use a @Get, and then compare the Method.

I'm trying to create a HEAD response with restlet. Unfortunatly there is ony a @Get annotation, but the restlet author states, that you have to use a @Get, and then compare the Method. As the documentation/specification says, there can be no body, but only a message header.

Now how to create a message header that will be send to the server, because the following code does not work, it sends this headers: 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));
}

The concrete code on server-side:

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

The client code:

@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
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消