无法在Play应用教程中使用WS.url()

时间:2018-03-03 09:25:56

标签: scala playframework project-structure

我正在使用Scala为Play框架做一个教程。我很早就进入了教程,我遇到了ws的问题。在我的课程中WS无法识别,虽然它说使用WS.url("url-here")并导入play.api.libs._我已经完成了这两项工作。我也尝试过使用ws.url("url-here") ......此处ws已被识别,但之后我收到了“无法解析符号'网址'”。这是我的build.sbt:

name := """play_hello"""
organization := "x.x"

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.12.3"

libraryDependencies ++= Seq(
"org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test,
"com.ning" % "async-http-client" % "1.9.29",
guice,
ws
)

以下是我班级的代码:

package controllers

import javax.inject.Inject

import com.ning.http.client.oauth.{ConsumerKey, RequestToken}
import play.api.Play.current
import play.api.libs._
import play.api.mvc._

import scala.concurrent.Future

class Application @Inject()(cc: ControllerComponents) extends 
AbstractController(cc){
 def tweets = Action.async{
credentials.map { case (consumerKey, requestToken) =>
  WS.url("http://stream.twitter.com")
  Future.successful{
    Ok
  }
}getOrElse{
  Future.successful{
    InternalServerError("Twitter credentials are missing!")
  }
}
}

def credentials: Option[(ConsumerKey, RequestToken)] = for{
apiKey <- current.configuration.getString("twitter.apiKey")
apiSecret <- current.configuration.getString("twitter.apiSecret")
token <- current.configuration.getString("twitter.token")
tokenSecret <- current.configuration.getString("twitter.tokenSecret")
}yield (
new ConsumerKey(apiKey, apiSecret),
new RequestToken(token, tokenSecret)
)
}

我认为这很可能是某种类型的依赖冲突问题。以下是项目structure中ws相关库的屏幕截图。我很感激为此找到解决方案的任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

解决方案是将ws: WSClient添加到Application类构造函数的参数中。在更新版本的ws库中已删除了独立的WS对象。

class Application @Inject()(cc: ControllerComponents, ws: WSClient) extends AbstractController(cc)

现在我可以使用:

ws.url("https://stream.twitter.com/1.1/statuses/filter.json")

另外根据play网站上的文档,如果由于某种原因无法使用注入的WSClient,那么你可以创建一个实例并使用它。