基本用法(Scala)
HTTP 请求是通过 WSClient 类创建的,你可以将其用作你自己的类中的注入参数。
import javax.inject.Inject
import play.api.libs.ws.WSClient
import scala.concurrent.{ExecutionContext, Future}
class MyClass @Inject() (
wsClient: WSClient
)(implicit ec: ExecutionContext){
def doGetRequest(): Future[String] = {
wsClient
.url("http://www.google.com")
.get()
.map { response =>
// Play won't check the response status,
// you have to do it manually
if ((200 to 299).contains(response.status)) {
println("We got a good response")
// response.body returns the raw string
// response.json could be used if you know the response is JSON
response.body
} else
throw new IllegalStateException(s"We received status ${response.status}")
}
}
}