![](/img/trans.png)
[英]Streaming an http response within a composed action in Play! Framework 2.1
[英]Play framework 2.1 HTTP HEAD method response
如何在Scala Play Framework 2.1上返回唯一的響應標頭(HTTP HEAD方法)?
您可以在GET路由旁邊添加HEAD路由,如下所示:
GET /assertion controllers.Assertion.get
HEAD /assertion controllers.Assertion.head
我想,在實現方法中,您可以調用GET方法並傳遞一個標志以禁止顯示主體。
返回EmptyContent作為內容怎么辦
Action {
....
Ok(EmptyContent())
}
不幸的是,有Java解決方案,但也許您會將其“轉換”為Scala,一般概念是:
autoHead(String originalPath)
使用WebServices轉發參數發送GET請求,並僅返回響應狀態。 X_FORWARD_FROM_HEAD
因此,如果您的操作在每次命中后將某些內容記錄到數據庫中,則可以避免HEAD
請求。 碼:
/**
* 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")));
}
路線:
HEAD / controllers.Application.autoHead(originalPath:String ?= "/")
HEAD /*originalPath controllers.Application.autoHead(originalPath:String)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.