本文整理汇总了Scala中play.api.libs.ws.WSRequest类的典型用法代码示例。如果您正苦于以下问题:Scala WSRequest类的具体用法?Scala WSRequest怎么用?Scala WSRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WSRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: payloadJson
//设置package包名称以及导入依赖的类
package neo4j.client
import com.typesafe.config.Config
import play.api.libs.json._
import play.api.libs.ws.{ WSAuthScheme, WSRequest, WSResponse }
import scala.concurrent.Future
trait Neo4jRestConnection {
protected val config: Config
protected val client = WSClient.client
val SERVER_ROOT_HOST = config.getString("neo4j-scala-dsl.neo4j.rest.host")
val SERVER_ROOT_PORT = config.getInt("neo4j-scala-dsl.neo4j.rest.port")
val SERVER_ROOT_URI = s"http://$SERVER_ROOT_HOST:$SERVER_ROOT_PORT"
val SERVER_ROOT_DATA_URI = s"$SERVER_ROOT_URI/db/data"
val SERVER_USERNAME = config.getString("neo4j-scala-dsl.neo4j.rest.username")
val SERVER_PASSWORD = config.getString("neo4j-scala-dsl.neo4j.rest.password")
val txUri = s"$SERVER_ROOT_DATA_URI/transaction/commit"
def payloadJson(statements: String*): JsObject =
Json.obj("statements" -> statements.map(s ? Map("statement" -> s)).toList)
def request(url: String): WSRequest = client.url(url)
.withHeaders(
("Content-Type", "application/json"),
("Accept", "application/json"))
.withAuth(SERVER_USERNAME, SERVER_PASSWORD, WSAuthScheme.BASIC)
def txCommit(queries: String*): Future[WSResponse] = {
println(s"txCommit: $queries")
request(txUri).post(payloadJson(queries: _*))
}
}
示例2: get
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.ups.controllers
import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.{OneServerPerSuite, WsScalaTestClient}
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.WSRequest
import uk.gov.hmrc.play.test.UnitSpec
trait DatabaseName {
val testName: String = "updated-print-suppressions"
}
trait TestServer
extends ScalaFutures
with DatabaseName
with UnitSpec
with BeforeAndAfterAll
with OneServerPerSuite
with WsScalaTestClient {
override implicit lazy val app = new GuiceApplicationBuilder()
.configure(Map("auditing.enabled" -> false,
"mongodb.uri" -> "mongodb://localhost:27017/updated-print-suppressions",
"application.router" -> "testOnlyDoNotUseInAppConf.Routes"
))
.build()
def `/preferences/sa/individual/print-suppression`(updatedOn: Option[String], offset: Option[String], limit: Option[String], isAdmin: Boolean = false) = {
val queryString = List(
updatedOn.map(value => "updated-on" -> value),
offset.map(value => "offset" -> value),
limit.map(value => "limit" -> value)
).flatten
if (isAdmin)
wsUrl("/test-only/preferences/sa/individual/print-suppression").withQueryString(queryString: _*)
else
wsUrl("/preferences/sa/individual/print-suppression").withQueryString(queryString: _*)
}
def get(url: WSRequest) = url.get().futureValue
}
示例3: ElasticsearchClient
//设置package包名称以及导入依赖的类
package utils
import javax.inject.{Inject, Singleton}
import play.api.libs.ws.{WSAuthScheme, WSClient, WSRequest, WSResponse}
import play.api.{Configuration, Environment, Logger}
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class ElasticsearchClient @Inject()(ws: WSClient, environment: Environment, configuration: Configuration)(implicit ec: ExecutionContext) {
val logger = Logger("ElasticsearchClient")
val elasticsearchUri: String = configuration.getString("elasticsearch.uri").getOrElse("http://localhost:9200")
val elasticsearchUser: Option[String] = configuration.getString("elasticsearch.user")
val elasticsearchPassword: Option[String] = configuration.getString("elasticsearch.password")
logger.info(s"Elasticsearch URI = $elasticsearchUri")
private def client(path: String): WSRequest = {
val sanitizedPath: String = if (path.startsWith("/")) {
path
} else {
s"/$path"
}
elasticsearchUser match {
case None => ws.url(s"$elasticsearchUri$sanitizedPath")
case Some(user) => ws.url(s"$elasticsearchUri$sanitizedPath").withAuth(user, elasticsearchPassword.getOrElse(""), WSAuthScheme.BASIC)
}
}
def bulk(body: String): Future[WSResponse] = {
client(s"/_bulk").post(body)
}
}
示例4: listPokemons
//设置package包名称以及导入依赖的类
package pokestats.pokeapi
import javax.inject.{Inject, Singleton}
import com.github.racc.tscg.TypesafeConfig
import play.api.http.HeaderNames.ACCEPT
import play.api.libs.ws.{WSClient, WSRequest}
import pokestats.pokeapi.model.{NamedApiResourceList, Pokemon, Type}
import pokestats.util.OptionSnakePickler._
import scala.concurrent.{ExecutionContext, Future}
trait PokeApi {
def listPokemons: Future[NamedApiResourceList]
def getPokemon(id: Int): Future[Pokemon]
def getType(id: Int): Future[Type]
}
@Singleton
class PokeApiClient @Inject()(
ws: WSClient,
@TypesafeConfig("pokestats.pokeapi.rootUrl") rootUrl: String)(
implicit context: ExecutionContext)
extends PokeApi {
override def listPokemons: Future[NamedApiResourceList] =
list[NamedApiResourceList]("pokemon")
override def getPokemon(id: Int): Future[Pokemon] =
get[Pokemon](s"pokemon/$id")
override def getType(id: Int): Future[Type] =
get[Type](s"type/$id")
private def get[A: Reader](path: String) = {
val req = request(path)
getAndParse[A](req)
}
private def list[A: Reader](path: String) = {
// Always get the full list by passing a very high limit
val req = request(path).withQueryStringParameters("limit" -> "999999")
getAndParse[A](req)
}
private def request(path: String) = {
ws.url(s"$rootUrl/$path")
.withHttpHeaders(ACCEPT -> "application/json")
}
private def getAndParse[A: Reader](request: WSRequest) = {
val response = request.get()
response.map(r => read[A](r.body))
}
}
示例5: ActionCallerSpec
//设置package包名称以及导入依赖的类
package services
import java.util.concurrent.TimeUnit
import akka.actor.ActorSystem
import akka.testkit.TestKit
import com.typesafe.config.ConfigFactory
import model.{Delay, HttpCall}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpecLike, Matchers}
import play.api.libs.ws.{WSClient, WSRequest, WSResponse}
import scala.concurrent.duration._
import org.scalatest.concurrent.{ScalaFutures}
import play.api.libs.json.Json
import play.mvc.Http.Status
import scala.concurrent.Future
object ActionCallerSpec {
// Define your test specific configuration here
val config =
"""
akka {
loglevel = "WARNING"
}
"""
}
class ActionCallerSpec extends TestKit(ActorSystem("InfraRedServiceSpec", ConfigFactory.parseString(ActionCallerSpec.config))) with FlatSpecLike with Matchers with MockFactory with ScalaFutures {
"The ActionCaller service" should "handle multiple http calls" in {
val ws = mock[WSClient]
val actionCaller = new DefaultActionCaller(ws, system)
val actions = Seq(HttpCall(method = "GET", path = "/jvc/AUX", order = 0), HttpCall(method = "GET", path = "/jvc/OFF", order = 1, delay = Some(Delay(3, TimeUnit.SECONDS))))
val mockRequest = mock[WSRequest]
val mockResponse = mock[WSResponse]
// (mockResponse.status _).expects().returns(Status.OK).anyNumberOfTimes()
(mockRequest.get: () => Future[WSResponse]).expects().returns(Future.successful(mockResponse)).anyNumberOfTimes()
(ws.url _).expects("/jvc/AUX").returns(mockRequest)
(ws.url _).expects("/jvc/OFF").returns(mockRequest)
actionCaller.call(actions).futureValue(timeout(4 seconds))
}
}
示例6: StandaloneWsClient
//设置package包名称以及导入依赖的类
package com.github.implicitdef.toolbox.http
import java.io.IOException
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.libs.ws.ahc.AhcWSClient
class StandaloneWsClient extends WSClient {
private implicit val actorSystem = ActorSystem()
private implicit val materializer = ActorMaterializer()
private val ahcWsClient = AhcWSClient()
override def underlying[T] = ahcWsClient.underlying[T]
override def url(url: String): WSRequest = ahcWsClient.url(url)
@scala.throws[IOException]
override def close(): Unit = {
ahcWsClient.close()
materializer.shutdown()
actorSystem.terminate()
}
}
示例7: AtlassianConnectHttpClient
//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.connect.play.ws
import javax.inject.Inject
import com.netaporter.uri.Uri
import UriImplicits._
import io.toolsplus.atlassian.connect.play.api.models.AtlassianHost
import io.toolsplus.atlassian.connect.play.auth.jwt.JwtGenerator
import io.toolsplus.atlassian.connect.play.ws.jwt.JwtSignatureCalculator
import play.api.libs.ws.{WSClient, WSRequest, WSSignatureCalculator}
class AtlassianConnectHttpClient @Inject()(ws: WSClient,
jwtGenerator: JwtGenerator) {
def authenticatedAsAddon(url: String)(
implicit host: AtlassianHost): WSRequest =
request(url, JwtSignatureCalculator(jwtGenerator))
private def request(url: String, signatureCalculator: WSSignatureCalculator)(
implicit host: AtlassianHost) = {
val requestUri = Uri.parse(url)
val absoluteUrl =
if (!requestUri.isAbsolute) absoluteRequestUrl(requestUri, host).toString
else url
ws.url(absoluteUrl).sign(signatureCalculator)
}
private def absoluteRequestUrl(requestUri: Uri, host: AtlassianHost) = {
val baseUri = Uri.parse(host.baseUrl)
val fullRelativeUri = Uri(
pathParts = baseUri.pathParts ++ requestUri.pathParts)
Uri(baseUri.toURI.resolve(fullRelativeUri.toURI))
}
}
示例8: ProviderActor
//设置package包名称以及导入依赖的类
package uk.mm.mpp.actors
import akka.actor.{Actor, Props}
import akka.pattern.pipe
import org.apache.commons.lang3.StringUtils._
import org.json4s._
import org.json4s.native.JsonMethods._
import play.api.Logger
import play.api.Play.current
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import uk.mm.mpp.actors.ProviderActor.{ProductRequest, ProductResponse}
import uk.mm.mpp.globals._
import scala.concurrent.ExecutionContext.Implicits.global
object ProviderActor {
def props(uid: String, port: Int) = Props(classOf[ProviderActor], uid, port)
case class ProductRequest()
case class ProductResponse(products: JArray)
}
class ProviderActor(uid: String, port: Int) extends Actor {
private lazy val request: WSRequest = WS.client.url(providerUrl)
.withFollowRedirects(false)
.withRequestTimeout(15000)
val logger = Logger(MPP_WORKER_PREFIX + getClass.getSimpleName + "_" + uid + "_" + port)
val providerUrl: String = "http://localhost:" + port + "/3rd/products"
def receive = {
case ProductRequest =>
request.get()
.map(productUpdateFrom)
.recover(withEmptyJsonArray)
.pipeTo(sender)
}
val withEmptyJsonArray: PartialFunction[Throwable, ProductResponse] = {
case _ => ProductResponse(JArray(List()))
}
def productUpdateFrom(response: WSResponse): ProductResponse = if (response.status == 200) {
logger.debug(s"from: [$providerUrl]: [${piedPiper(response)}]")
ProductResponse(parseJsonFrom(response))
} else {
logger.warn(s"from: [$providerUrl]: [${response.body}]")
ProductResponse(JArray(List()))
}
def piedPiper(response: WSResponse) = {
abbreviate(replacePattern(response.body, """\s{2,}""", " "), 30)
}
def parseJsonFrom(response: WSResponse) = parse(response.body).asInstanceOf[JArray]
}
示例9: Http
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support
import play.api.Play.current
import play.api.http.{HeaderNames, MimeTypes}
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import play.api.mvc.Results
import uk.gov.hmrc.play.http.ws.WSHttpResponse
import uk.gov.hmrc.play.http.{HeaderCarrier, HttpResponse}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
object Http {
def get(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.get()
}
def post(url: String, body: String, headers: Seq[(String, String)] = Seq.empty)
(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.withHeaders(headers: _*).post(body)
}
def postEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
import play.api.http.Writeable._
request.post(Results.EmptyContent())
}
def putEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
import play.api.http.Writeable._
request.put(Results.EmptyContent())
}
def delete(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.delete()
}
private def perform(url: String)(fun: WSRequest => Future[WSResponse])(implicit hc: HeaderCarrier): WSHttpResponse =
await(fun(WS.url(url).withHeaders(hc.headers: _*).withRequestTimeout(20000 milliseconds)).map(new WSHttpResponse(_)))
private def await[A](future: Future[A]) = Await.result(future, Duration(10, SECONDS))
}
class Resource(path: String, port: Int) {
private def url() = s"http://localhost:$port$path"
def get()(implicit hc: HeaderCarrier = HeaderCarrier()) = Http.get(url)(hc)
def postAsJson(body: String)(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.post(url, body, Seq(HeaderNames.CONTENT_TYPE -> MimeTypes.JSON))(hc)
def postEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.postEmpty(url)(hc)
def putEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.putEmpty(url)(hc)
}
示例10: WattmeterClient
//设置package包名称以及导入依赖的类
package ws
import java.time.Clock
import model.LocationRepository
import model.sensor.{IdentityMeasurementAggregationStrategy, Measurement, SensorRepository}
import play.api.Logger
import play.api.libs.ws.{WSClient, WSRequest}
import scala.concurrent.ExecutionContext.Implicits.global
class WattmeterClient(
ws: WSClient,
sensorRepository: SensorRepository,
locationRepository: LocationRepository,
clock: Clock
) {
val request: WSRequest = ws.url("http://192.168.100.240/meas.xml")
def queryWattmeter():Unit = {
request.get().map(response => {
val l1Power = (response.xml \ "I1" \ "P").text.toDouble
val l2Power = (response.xml \ "I2" \ "P").text.toDouble
val l3Power = (response.xml \ "I3" \ "P").text.toDouble
Logger.debug(s"Received response from wattmeter L1:${l1Power} W, L2: ${l2Power} W, L3: ${l3Power} W")
val now = clock.instant()
val sensor = sensorRepository.findOrCreateSensor(
location = locationRepository.findOrCreateLocation("main-switchboard"),
name = "wattrouter"
)
sensor.addMeasurement(
measurement = Measurement(l1Power, now),
measuredPhenomenon = sensor.findOrCreatePhenomenon("L1 Power", "W", IdentityMeasurementAggregationStrategy)
)
sensor.addMeasurement(
measurement = Measurement(l2Power, now),
measuredPhenomenon = sensor.findOrCreatePhenomenon("L2 Power", "W", IdentityMeasurementAggregationStrategy)
)
sensor.addMeasurement(
measurement = Measurement(l3Power, now),
measuredPhenomenon = sensor.findOrCreatePhenomenon("L3 Power", "W", IdentityMeasurementAggregationStrategy)
)
})
}
}
示例11: BotMessageSender
//设置package包名称以及导入依赖的类
package models
import play.api.Play
import play.api.libs.ws.{WSClient, WSRequest, WSResponse}
import scala.concurrent.Future
case class BotMessageSender(ws: WSClient) {
private val USERNAME = "surveybot"
private val TOKEN = Play.current.configuration.getString("slack.botUserToken").get
private val SLACK_API_URL = "https://slack.com/api/chat.postMessage"
def sendMessage(botMessage: BotMessage): Future[WSResponse] = {
buildRequest(botMessage).get()
}
def buildRequest(botMessage: BotMessage): WSRequest = {
ws.url(SLACK_API_URL)
.withQueryString(
("username", USERNAME),
("channel", s"@${botMessage.channel}"),
("token", TOKEN),
("text", botMessage.text))
}
}
示例12: ShortUrl
//设置package包名称以及导入依赖的类
package models
import org.h2.index.HashIndex
import play.api.libs.json.{Writes, Format, Json}
import play.api.libs.ws.{WSRequest, WS}
import play.api.Play.current
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random
case class ShortUrl(hash: String, fullUrl: String)
object ShortUrl {
implicit val shortUrlFmt: Format[ShortUrl] = Json.format[ShortUrl]
def lookup(hash: String)(implicit ec: ExecutionContext): Future[Option[ShortUrl]] = {
//todo:read the mapping from db and return ShortUrl obj
val fullurl: Future[Option[String]] = ShorturlDAO.findByHash(hash)
fullurl.map((result: Option[String]) => {
result.map{ (fullurl: String) =>
ShortUrl(hash,fullurl)
}
})
}
def shorten(fullUrl: String)(implicit ec: ExecutionContext): Future[ShortUrl] = {
//todo:compute a unique hash,done
nextUniqueId.map{nextId =>
hashId(nextId)
}.flatMap{hash =>
val insertFuture = ShorturlDAO.saveMapping(hash,fullUrl)
insertFuture.map{ _ =>
ShortUrl(hash,fullUrl)
}
}
}
//val countIoServiceUrl: String = "http://count.io/vb/urlshortner/hash+"
//val countioRequestHolder: WSRequest = WS.url(countIoServiceUrl)
private def nextUniqueId(implicit ex: ExecutionContext): Future[Int] = {
val r = new Random().nextInt(30)
Future.successful(r)
}
private val hashIndex: String = "abcdefghABCDEFGH123456"
private def hashId(id: Int,acc: String = ""): String = {
//val hashInd = hashIndex + url
id match {
case 0 => acc
case _ => hashId(id / hashIndex.length, acc + hashIndex.charAt(id % hashIndex.length))
}
}
}
示例13: MixedPlaySpecWithNoDefaultApp
//设置package包名称以及导入依赖的类
import org.scalatest.concurrent.{Eventually, IntegrationPatience}
import org.scalatest.{MustMatchers, OptionValues, fixture}
import org.scalatestplus.play.{PortNumber, WsScalaTestClient}
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.mvc.Call
abstract class MixedPlaySpecWithNoDefaultApp extends fixture.WordSpec
with MustMatchers
with OptionValues
with MixedFixturesWithNoDefaultApp
with Eventually
with IntegrationPatience
with WsScalaTestClient
{
//def wsCall(call: Call)(implicit portNumber: PortNumber, wsClient: WSClient): WSRequest = doCall(call.url, wsClient, portNumber)
// def wsUrl(url: String)(implicit portNumber: PortNumber, wsClient: WSClient): WSRequest = doCall(url, wsClient, portNumber)
//private def doCall(url: String, wsClient: WSClient, portNumber: PortNumber) = {
// wsClient.url("http://localhost:" + portNumber.value + url)
//}
}
示例14: WSClientWithFlow
//设置package包名称以及导入依赖的类
package microtools.ws
import microtools.models.{AuthRequestContext, ExtraHeaders, RequestContext, ServiceName}
import play.api.http.HeaderNames
import play.api.libs.ws.{WSClient, WSRequest}
class WSClientWithFlow(val underlying: WSClient) {
private[this] object ForwardProto extends Enumeration {
type Type = Value
val HTTP = Value("http")
val HTTPS = Value("https")
}
def url(rawUrl: String)(implicit ctx: RequestContext): WSRequest = {
val (url, forwardProto): (String, ForwardProto.Type) =
if (rawUrl.startsWith("https:"))
s"http:${rawUrl.drop(6)}" -> ForwardProto.HTTPS
else rawUrl -> ForwardProto.HTTP
underlying
.url(url)
.withHeaders(ExtraHeaders.FLOW_ID_HEADER -> ctx.flowId,
HeaderNames.X_FORWARDED_PROTO -> forwardProto.toString)
}
def urlWithAuthFromContext(rawUrl: String)(implicit ctx: AuthRequestContext): WSRequest = {
url(rawUrl)
.withHeaders(HeaderNames.AUTHORIZATION -> s"Bearer ${ctx.token}")
}
def urlWithServiceAuth(rawUrl: String)(implicit serviceName: ServiceName,
ctx: RequestContext): WSRequest = {
url(rawUrl)
.withHeaders(
ExtraHeaders.AUTH_SUBJECT_HEADER -> s"service/$serviceName"
)
}
}
示例15: LetsEncryptWSClient
//设置package包名称以及导入依赖的类
package controllers
import akka.stream.Materializer
import com.typesafe.config.ConfigFactory
import play.api.inject.ApplicationLifecycle
import play.api.libs.ws.ahc.{AhcConfigBuilder, AhcWSClient, AhcWSClientConfig}
import play.api.libs.ws.{WSClient, WSConfigParser, WSRequest}
import play.api.{Configuration, Environment}
import scala.concurrent.Future
import contexts._
class LetsEncryptWSClient(lifecycle: ApplicationLifecycle,
env: Environment)(implicit mat: Materializer, wsEc: WSExecutionContext) extends WSClient {
private val propsConfig = ConfigFactory.systemProperties()
private val wsConfig = ConfigFactory.load(propsConfig.withFallback(ConfigFactory.parseString(
"""
|play.ws {
| ssl {
| trustManager = {
| stores = [
| # Seems to be required for https://helloworld.letsencrypt.com
| { type = "PEM", path = "./conf/dst-x3-root.pem" }
| { type = "PEM", path = "./conf/letsencrypt-authority-x1.pem" }
| ]
| }
| }
|}
""".stripMargin)))
private lazy val client = {
val configuration = Configuration.reference ++ Configuration(wsConfig)
val parser = new WSConfigParser(configuration, env)
val config = new AhcWSClientConfig(wsClientConfig = parser.parse())
val builder = new AhcConfigBuilder(config)
val client = AhcWSClient(builder.build())
lifecycle.addStopHook { () =>
Future(client.close())
}
client
}
override def underlying[T]: T = client.underlying[T]
override def url(url: String): WSRequest = client.url(url)
override def close(): Unit = client.close()
}