2
votes

How can I return a only response header(HTTP HEAD method) on scala play framework 2.1?

3

3 Answers

0
votes

Unfortunatelly there is Java solution but maybe you will 'convert' it to Scala, general concept is:

  • Catch HEAD request send it to dedicated method
  • The method autoHead(String originalPath) sends a GET request using WebServices forwarding params and returning only status of the response.
  • It adds additional header X_FORWARD_FROM_HEAD so if ie your action is logging something to the DB after each hit you can avoid that for HEAD requests.

code:

/**
 * Tries to get headers of resource with WebServices and return headers only.
 *
 * @param originalPath Path of the resource
 * @return Headers for HEAD request
 * @throws IllegalAccessException
 */
public static Result autoHead(String originalPath) throws IllegalAccessException {


    WS.WSRequestHolder forwardedRequest = WS.url("http://" + request().host() + request().path());
    // this header will allow you to make additional choice i.e. avoid tracking the request or something else
    // see condition in index() action
    forwardedRequest.setHeader("X_FORWARD_FROM_HEAD", "true");

    // Forward original headers
    for (String header : request().headers().keySet()) {
        forwardedRequest.setHeader(header, request().getHeader(header));
    }

    // Forward original queryString
    for (String key : request().queryString().keySet()) {
        for (String val : request().queryString().get(key)) {
            forwardedRequest.setQueryParameter(key, val);
        }
    }

    // Call the same path but with GET
    WS.Response wsResponse = forwardedRequest.get().get();

    // Set returned headers to the response
    for (Field f : Http.HeaderNames.class.getFields()) {
        String headerName = f.get(null).toString();
        if (wsResponse.getHeader(headerName) != null) {
            response().setHeader(headerName, wsResponse.getHeader(headerName));
        }
    }

    return status(wsResponse.getStatus());
}

/**
 * Checks if request if forwarded from HEAD request
 *
 * @return true if 'X_FORWARD_FROM_HEAD' header exists and is set to true
 */
public static boolean forwardedFromHead() {
    return (request().getHeader("X_FORWARD_FROM_HEAD") != null && "true".equals(request().getHeader("X_FORWARD_FROM_HEAD")));
}

routes:

HEAD    /                  controllers.Application.autoHead(originalPath:String ?= "/")
HEAD    /*originalPath     controllers.Application.autoHead(originalPath:String)
0
votes

You can add a HEAD route, next to the GET route, like this:

GET   /assertion                        controllers.Assertion.get
HEAD  /assertion                        controllers.Assertion.head

In the implementing method, you can call the GET method and pass a flag to suppress the body, I guess.

0
votes

What about returning EmptyContent as a content

     Action {
        ....
        Ok(EmptyContent())  
     }