我正在从 Play 应用程序访问 SSL 安全页面。当页面的证书不可信时(因为它已过期或自签名或可能是其他任何原因),我想从我的通话中提取此信息并相应地执行一些操作。当我在浏览器中访问这样的页面时,它会警告我证书有问题。当我在游戏中写这样的东西时(这里的 https 页面有一个错误的证书):
package controllers
import play.api.mvc.{Action, Controller}
import play.api.libs.ws.WS
import java.util.concurrent.TimeUnit
object CallHttpsController extends Controller{
def callHttps() = Action {
val url = "https://xceed.no-ip.org/"
val response: play.api.libs.ws.Response = WS.url(url).get.await(3, TimeUnit.SECONDS).get
response.status match {
case OK => Ok("Got response: " + response.body)
case _ => Ok("Something went wrong: "+response.status+" "+response.body)
}
}
}
响应状态正常,我希望它会抛出证书有问题的异常。
当证书不可信时,是否可以调用这样的页面并获得异常?是否支持默认播放?有没有人有类似的问题/需要?
提前致谢。
更新 #1: 感谢 Ning 的提示。我在构建脚本中添加了依赖项:
lazy val appDependencies = Seq(
"com.ning" % "async-http-client" % "1.7.5"
)
图书馆本身确实很有帮助。但是,要按预期使用 SSL,显然它需要初始化 SSL 上下文。我尝试了以下代码:
def callHttps() = Action {
try{
val url = "https://xceed.no-ip.org/"
val response: play.api.libs.ws.Response = WS.url(url).get.await(3, TimeUnit.SECONDS).get // => No problem here
Console.println(WS.client.getConfig.getSSLContext) // => null
val sslContext = SSLContext.getDefault;
val playConfig = play.api.Play.maybeApplication.map(_.configuration)
val asyncHttpConfig = new AsyncHttpClientConfig.Builder()
.setConnectionTimeoutInMs(playConfig.flatMap(_.getMilliseconds("ws.timeout")).getOrElse(120000L).toInt)
.setRequestTimeoutInMs(playConfig.flatMap(_.getMilliseconds("ws.timeout")).getOrElse(120000L).toInt)
.setFollowRedirects(playConfig.flatMap(_.getBoolean("ws.followRedirects")).getOrElse(true))
.setUseProxyProperties(playConfig.flatMap(_.getBoolean("ws.useProxyProperties")).getOrElse(true))
.setSSLContext( sslContext )
playConfig.flatMap(_.getString("ws.useragent")).map { useragent =>
asyncHttpConfig.setUserAgent(useragent)
}
val innerClient = new AsyncHttpClient(asyncHttpConfig.build())
val resp = innerClient.prepareGet(url).execute().get() // => exception
Console.println("All OK")
Ok("Got response: " + resp.getResponseBody)
}
catch {
case e: Exception =>
var cause = e.getCause
while (cause != null) {
Console.println("Caused by: \n" + e.getLocalizedMessage + "\n" + e.getStackTraceString)
cause = cause.getCause
}
Ok("Got Exception: " + e.getLocalizedMessage + "\n" + e.getStackTraceString)
}
}
从 WS 源代码中提取了一个客户端初始化,并将默认 SSL 上下文传递给客户端。然后调用按预期失败。将尝试通过游戏筹集门票......干杯!
更新#2: 门票现已解决,将成为游戏 2.0.4 的一部分 https://play.lighthouseapp.com/projects/82401/tickets/655-ws-call-wont-fail-upon-https-使用错误证书调用页面
更新#3: 现在默认设置默认的 ssl 上下文。要在应用程序配置文件中关闭它,请设置 ws.acceptAnyCertificate=true
有关更多信息,请参阅 WS.scala 代码: https ://github.com/playframework/Play20/blob/master/framework/src/play/src/main/scala/play/api/libs/ws/WS.scala