我有一个简单的测试Scala应用程序,该应用程序阻止了HTTP请求:
build.sbt
name := "hello"
version := "1.0"
scalaVersion := "2.11.2"
libraryDependencies += "com.typesafe.play" %% "play-ws" % "2.4.0-M1"
测试规模
import play.api.libs.json._
import play.api.libs.ws._
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
object Test {
def main(args: Array[String]) = {
val wsClient = WS.client
val body = getBody(wsClient.url("http://example.com/").get())
println(s"body: $body")
}
def getBody(future: Future[WSResponse]) = {
val response = Await.result(future, Duration.Inf);
if (response.status != 200)
throw new Exception(response.statusText);
response.body
}
}
此应用程序失败并显示:
Exception in thread "main" java.lang.RuntimeException: There is no started application
如何解决这个问题?
编辑Play 2.5:
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc.AhcWSClient
import scala.concurrent.Future
object Main {
import scala.concurrent.ExecutionContext.Implicits._
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val wsClient = AhcWSClient()
call(wsClient)
.andThen { case _ => wsClient.close() }
.andThen { case _ => system.terminate() }
}
def call(wsClient: WSClient): Future[Unit] = {
wsClient.url("http://www.google.com").get().map { response =>
val statusText: String = response.statusText
println(s"Got a response $statusText")
}
}
}
请参阅:
有关独立WSClient用法的更多详细示例。如果要从早期版本迁移,请参阅https://www.playframework.com/documentation/2.5.x/Migration25#Play-WS-upgrades-to-AsyncHttpClient-2
对于Play 2.4:
不要对HTTPS使用原始的AsyncHttpClientConfig.Builder -它不会使用主机名验证来配置安全的SSLContext。
您可以使用以下代码创建新的WSClient实例:
import play.api.libs.ws.ning._
import play.api.libs.ws._
val config = new NingAsyncHttpClientConfigBuilder(DefaultWSClientConfig()).build()
val builder = new AsyncHttpClientConfig.Builder(config)
val wsClient:WSClient = new NingWSClient(builder.build())
请注意,这将启动线程,除非您关闭客户端,否则这些线程将无法关闭:
wsClient.underlying[NingWSClient].close()
如果不关闭它,可能会遇到内存泄漏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句