Play Framework 2.1:Scala:如何获得整个基本URL(包括协议)?

时间:2013-02-13 21:32:58

标签: scala request playframework-2.1

目前,我可以从request获取主机,其中包括域和可选端口。不幸的是,它不包括协议(http vs https),因此我无法为网站本身创建绝对网址。

object Application extends Controller {
  def index = Action { request =>
    Ok(request.host + "/some/path") // Returns "localhost:9000/some/path"
  }
}

有没有办法从请求对象中获取协议?

5 个答案:

答案 0 :(得分:9)

实际上有一种简单的方法可以使用反向路由器用来实现类似功能的Call类。 鉴于您属于隐式请求的范围,您可以执行以下操作:

new Call(request.method, input.request).absoluteURL()

它将为您提供完整的URL(协议,主机,路由和参数)。

答案 1 :(得分:6)

在Play 2.3及更高版本中,您可以使用the secure property of the Request类。

答案 2 :(得分:4)

我认为没有。

解决方法是使用//domain.com/path使用application.conf

然而,这并不能帮助您处理电子邮件中的链接。在这种情况下,您可以将协议放在{{1}}中。在大多数情况下,差异是因为生产支持https而开发不支持。

我还没有找到上述解决方法不起作用的情况。

答案 3 :(得分:3)

实际上,如果是http或https,您的portnumber会给您。

使用https支持JAVA_OPTS=-Dhttps.port=9001 play start

启动Play服务器

这是一段代码片段(您可以使用正则表达式使验证更稳定,从属性中获取https端口号...)

def path = Action { request =>
    val path = 
      if(request.host.contains(":9000"))
        "http://" + request.host + "/some/path"
      else
        "https://" + request.host + "/some/path"
    Ok(path)
  }

代码将返回

http://ServerIp:9000/some/path if it's thru http
https://ServerIp:9001/some/path if it's thru https

答案 4 :(得分:0)

我的解决方案是将url的开头作为javascript的附加参数传递。 application.conf解决方案对我不起作用,因为可以在http和https上访问相同的应用程序,但是来自不同的子网和域。