关于Scala:如何在正常的sbt项目中使用play ws库而不是play?

How do i use play ws library in normal sbt project instead of play?

当我尝试在正常的sbt项目而不是play项目中使用Play WS库时,我必然会使用play.api.Play.current并得到java.lang.RuntimeException:尝试时"没有启动的应用程序"运行该应用程序。


在2.4.x中的用法

1
2
3
4
import play.api.libs.ws.ning.NingWSClient  

val wsClient = NingWSClient()
wsClient.url("http://wwww.something.com").get()

build.sbt:

1
libraryDependencies +="com.typesafe.play" %%"play-ws" %"2.4.3"

在2.5.x中的用法

1
2
3
4
5
6
7
8
9
import play.api.libs.ws.ahc.AhcWSClient

implicit val actorSystem = ActorSystem()
implicit val materializer = ActorMaterializer()
wsClient.url("http://wwww.something.com").get()

//at the very end, to shutdown stuff cleanly :
wsClient.close()
actorSystem.terminate()

build.sbt:

1
libraryDependencies +="com.typesafe.play" %%"play-ws" %"2.5.4"

日志

正如评论中指出的那样,默认情况下,您可能会从基础async-http-client那里收到一堆详细的日志。解决该问题的一种方法是开始配置logback.xml,并将其放置在src / main / resources

中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<configuration>

<conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" />


    <encoder>
        <!-- The logging pattern, you might want to adapt it -->
        <pattern>%d %coloredLevel %t - %logger - %message%n%xException</pattern>
    </encoder>
</appender>

<!-- Here you can change the levels of specific loggers -->
<logger name="somelogger" level="INFO" />

<!-- Default logging level for every logger -->
<root level="ERROR">
   
</root>

</configuration>


要在游戏之外使用play-ws,请参见文档的"使用WSClient "部分:http://www.playframework.com/documentation/2.3.x/ScalaWS

1
2
3
val builder = new com.ning.http.client.AsyncHttpClientConfig.Builder()
val client = new play.api.libs.ws.ning.NingWSClient(builder.build())
val response = client.url(url).get()