本文整理汇总了Scala中play.api.libs.ws.WSResponse类的典型用法代码示例。如果您正苦于以下问题:Scala WSResponse类的具体用法?Scala WSResponse怎么用?Scala WSResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WSResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: myPublicAddress
//设置package包名称以及导入依赖的类
package org.zalando.hutmann.spec
import org.scalatest.concurrent.PatienceConfiguration.Interval
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import org.scalatestplus.play.{ PlaySpec, PortNumber, WsScalaTestClient }
import play.api.Application
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.{ WSClient, WSResponse }
trait PlayUnitSpec extends PlaySpec with ScalaFutures with WsScalaTestClient {
def myPublicAddress(): String
implicit val portNumber: PortNumber
def callWs(testPaymentGatewayURL: String)(implicit app: Application): WSResponse = {
implicit val wSClient = app.injector.instanceOf[WSClient]
val callbackURL = s"http://${myPublicAddress()}/callback"
whenReady(
wsUrl(testPaymentGatewayURL)
.withQueryStringParameters("callbackURL" -> callbackURL)
.withHttpHeaders(HeaderNames.ACCEPT -> MimeTypes.TEXT)
.get(),
Interval(Span(10, Seconds))
) { result =>
result
}
}
}
示例2: 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: _*))
}
}
示例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: config
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux
import com.pygmalios.reactiveinflux.response.ReactiveInfluxJsonResultException
import play.api.libs.ws.{WSClient, WSRequestHolder, WSResponse}
import scala.concurrent.Future
trait ReactiveInfluxCore {
def config: ReactiveInfluxConfig
def execute[R <: ReactiveInfluxCommand](command: R): Future[command.TResult]
}
trait ReactiveInfluxCommand extends Serializable {
type TResult <: Any
def apply(wsRequest: WSRequestHolder, wsResponse: WSResponse): TResult = {
try {
responseFactory(wsResponse).result
}
catch {
case ex: ReactiveInfluxJsonResultException =>
throw new ReactiveInfluxResultError(ex.errors, wsRequest)
case ex: Exception =>
throw new ReactiveInfluxException(s"Response processing failed!\n [$wsResponse]\n [${wsRequest.method}]\n [${wsRequest.url}\n [${wsResponse.body}]]", ex)
}
}
def logInfo: String = ""
protected def responseFactory(httpResponse: WSResponse): ReactiveInfluxResult[TResult]
}
trait ReactiveInfluxResult[+T] extends Serializable {
def result: T
}
示例5: QueryCommand
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query
import java.net.URI
import com.pygmalios.reactiveinflux.impl.OptionalParameters
import com.pygmalios.reactiveinflux.response.PlayWSJsonResponse
import com.pygmalios.reactiveinflux.{BigDecimalValue, BooleanValue, Query, QueryResult, ReactiveInfluxDbName, ReactiveInfluxException, Result, Rfc3339, Series, StringValue, TimeFormat, Value}
import play.api.libs.json._
import play.api.libs.ws.{WSClient, WSResponse}
class QueryCommand(baseUri: URI, dbName: ReactiveInfluxDbName, qs: Seq[Query], params: QueryParameters) extends BaseQueryCommand(baseUri) {
override type TResult = Seq[QueryResult]
override protected def responseFactory(wsResponse: WSResponse) = {
val timeFormat: TimeFormat = params.epoch.getOrElse(Rfc3339)
new QueryCommandResult(wsResponse, qs, timeFormat)
}
override def httpRequest(ws: WSClient) = {
val q = qs.map(_.influxQl).mkString(";")
ws.url(qUri(q).toString)
}
override def otherParams = OptionalParameters(
QueryParameters.dbQ -> Some(dbName.value),
QueryParameters.epochQ -> params.epoch.map(_.q),
QueryParameters.chunkSizeQ -> params.chunkSize.map(_.toString)
)
}
private[reactiveinflux] class QueryCommandResult(wsResponse: WSResponse, qs: Seq[Query], timeFormat: TimeFormat)
extends PlayWSJsonResponse[Seq[QueryResult]](wsResponse) {
import JsonResultFormat._
override def result: Seq[QueryResult] = qs.zip(results).map {
case (q, jsResult) =>
QueryResult(q, jsToResult(jsResult.as[JsonResult]))
}
private def jsToResult(jsonResult: JsonResult): Result = Result(jsonResult.series.map(jsToSeries))
private def jsToSeries(jsonSeries: JsonSeries): Series = Series(
name = jsonSeries.name,
columns = jsonSeries.columns,
values = jsonSeries.values.map(jsRow => jsRow.flatMap(jsToValue)),
timeFormat = timeFormat
)
private def jsToValue(jsValue: JsValue): Option[Value] = jsValue match {
case JsString(value) => Some(StringValue(value))
case JsNumber(value) => Some(BigDecimalValue(value))
case JsBoolean(value) => Some(BooleanValue(value))
case JsNull => None
case other => throw new ReactiveInfluxException(s"Unsupported JSON value type! [$other]")
}
}
object QueryCommandResult {
val seriesField = "series"
}
示例6: DropDatabaseCommand
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query
import java.net.URI
import com.pygmalios.reactiveinflux.ReactiveInfluxDbName
import com.pygmalios.reactiveinflux.error.{DatabaseNotFound, ReactiveInfluxError}
import com.pygmalios.reactiveinflux.response.EmptyJsonResponse
import play.api.libs.ws.{WSClient, WSResponse}
class DropDatabaseCommand(baseUri: URI, dbName: ReactiveInfluxDbName, failIfNotExists: Boolean)
extends BaseQueryCommand(baseUri) {
import DropDatabaseCommand._
override type TResult = Unit
override protected def responseFactory(wsResponse: WSResponse) =
new DropDatabaseResponse(wsResponse, failIfNotExists)
override def httpRequest(ws: WSClient) = ws.url(qUri(queryPattern.format(dbName.value)).toString)
}
object DropDatabaseCommand {
val queryPattern = "DROP DATABASE %s"
}
class DropDatabaseResponse(wsResponse: WSResponse, failIfNotExists: Boolean)
extends EmptyJsonResponse(wsResponse) {
override protected def errorHandler: PartialFunction[ReactiveInfluxError, Option[ReactiveInfluxError]] = {
case DatabaseNotFound(_) if !failIfNotExists => None
}
}
示例7: ExampleApplication
//设置package包名称以及导入依赖的类
package com.example
import java.net.URI
import com.pygmalios.reactiveinflux.ReactiveInfluxDbName
import com.pygmalios.reactiveinflux.command.query.BaseQueryCommand
import com.pygmalios.reactiveinflux.itest.ITestConfig
import com.pygmalios.reactiveinflux.response.EmptyJsonResponse
import com.pygmalios.reactiveinflux.{ReactiveInflux, ReactiveInfluxCore}
import org.scalatest.FunSuite
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import play.api.libs.ws.{WSClient, WSResponse}
class ExampleApplication extends FunSuite with ScalaFutures with IntegrationPatience {
test("Execute custom command") {
val reactiveInflux = ReactiveInflux(config = Some(ITestConfig.config))
try {
implicit val dbName = ReactiveInfluxDbName("ExampleApplicatixon")
val db = reactiveInflux.database
try {
val core = reactiveInflux.asInstanceOf[ReactiveInfluxCore]
whenReady(core.execute(new CustomQueryCommand(core.config.url)).failed) { ex =>
}
}
finally {
db.drop()
}
}
finally {
reactiveInflux.close()
}
}
}
class CustomQueryCommand(baseUri: URI) extends BaseQueryCommand(baseUri) {
override type TResult = Unit
override protected def responseFactory(wsResponse: WSResponse) = new CustomQueryCommandResponse(wsResponse)
override def httpRequest(ws: WSClient) = ws.url(qUri("WHATEVER").toString)
}
class CustomQueryCommandResponse(wsResponse: WSResponse) extends EmptyJsonResponse(wsResponse)
示例8: PlayWsHttpResponse
//设置package包名称以及导入依赖的类
package http.client.connection.impl
import http.client.connection.HttpConnection
import http.client.request.HttpRequest
import http.client.response.{HttpHeader, HttpResponse}
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ning.NingWSClient
import scala.concurrent.{ExecutionContext, Future}
private[impl] case class PlayWsHttpResponse(status: Int, headers: Seq[HttpHeader], response: WSResponse) extends HttpResponse {
override val statusText = response.statusText
override val body = response.body
override val bodyAsBytes = response.bodyAsBytes
override def json = response.json
}
private[impl] object PlayWsHttpResponse {
def apply(wsReponse: WSResponse): PlayWsHttpResponse =
PlayWsHttpResponse(
wsReponse.status,
// turn Map[String, Seq[String]] into Seq[HttpHeader]
wsReponse.allHeaders.flatMap { kv ? kv._2.map { v ? HttpHeader(kv._1, v) } }.toSeq,
wsReponse)
}
class PlayWSHttpConnection extends HttpConnection {
implicit val client = NingWSClient()
private def queryStringToSeq(fields: Map[String, Seq[String]]): Seq[(String, String)] =
fields.flatMap(keyAndValues ? {
val key = keyAndValues._1
keyAndValues._2.map(value ? (key, value)).toList
}).toSeq
override def shutdown() = client.close()
override def makeRequest(request: HttpRequest)(implicit ec: ExecutionContext): Future[HttpResponse] = {
println(request.baseUrl + request.relativeUrl + " " + request.queryString)
val r = client
.url(request.baseUrl + request.relativeUrl)
.withHeaders(request.headers.map({ h ? h.name ? h.value }): _*)
.withQueryString(queryStringToSeq(request.queryString): _*)
.withMethod(request.method.name)
val req = if (request.body.isDefined) {
val r2 = r.withBody(request.body.get)
r2.execute()
} else {
r.execute()
}
req.map(PlayWsHttpResponse.apply)
}
}
示例9: 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]
}
示例10: UserControllerTest
//设置package包名称以及导入依赖的类
package users.controllers
import commons.models.Login
import play.api.libs.json.{JsValue, Json}
import play.api.libs.ws.WSResponse
import testhelpers.PlayWithFoodWithServerBaseTest
import users.controllers.mappings.UserJsonMappings._
import users.models.{User, UserId}
import users.repositories.UserRepo
class UserControllerTest extends PlayWithFoodWithServerBaseTest {
val apiPath: String = "users"
"user API" should {
"return list with Marek" in {
implicit val c = components
import c._
// given
val user = User(UserId(1), Login("Marek"))
val persistedUser = runAndAwaitResult(userRepo.create(user))
// when
val response: WSResponse = await(wsUrl(s"/$apiPath").get)
// then
response.status.mustBe(OK)
val expectedBody: JsValue = Json.toJson(List(persistedUser))
response.body.mustBe(expectedBody.toString())
}
}
}
示例11: getToken
//设置package包名称以及导入依赖的类
package controllers
import java.nio.file.Path
import com.typesafe.config.ConfigFactory
import play.api.libs.ws.{WSClient, WSResponse}
import scala.concurrent.Future
trait GitHubServer {
val config = ConfigFactory.load().getConfig("devgym.github")
val clientId = config.getString("client-id")
val clientSecret = config.getString("client-secret")
val redirectUri = config.getString("uri")
def getToken(code: String)(implicit ws: WSClient): Future[WSResponse] = {
ws.url("https://github.com/login/oauth/access_token")
.withQueryString(
"client_id" -> clientId,
"client_secret" -> clientSecret,
"code" -> code,
"redirect_uri" -> redirectUri
)
.withHeaders("Accept" -> "application/json")
.withMethod("POST")
.get()
}
def query(token: String, path: Path)(implicit ws: WSClient): Future[WSResponse] = {
ws.url(s"https://api.github.com/$path")
.withHeaders("Authorization" -> s"token $token")
.get()
}
}
示例12: Halo5Api
//设置package包名称以及导入依赖的类
package haloapi
import javax.inject._
import com.google.inject.ConfigurationException
import play.api.{Configuration, Play}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.ws.{WSClient, WSResponse}
class Halo5Api @Inject() (ws: WSClient, configuration: Configuration) {
val primaryKey = configuration.getString("halo.api.primary").getOrElse(throw new RuntimeException("Halo 5 API primary key not configured"))
val subscriptionKeyHeader = "Ocp-Apim-Subscription-Key"
def getMatchesForUser(gamerTag: String) = {
val urlTemplate = s"https://www.haloapi.com/stats/h5/players/$gamerTag/matches"
val request = ws.url(urlTemplate).withHeaders(subscriptionKeyHeader -> primaryKey)
request.get().map(transformMatchResponse)
}
def transformMatchResponse(response: WSResponse) = {
response.json
}
}
示例13: WSClientImplicits
//设置package包名称以及导入依赖的类
package anchorman.media
import play.api.libs.ws.WSResponse
object WSClientImplicits {
implicit class WSResponseOps(response: WSResponse) {
def filename(url: String): String =
contentDispositionFilename getOrElse urlFilename(url)
val ContentDispositionFilename = ".*filename=\"([^;]+)\"".r
def contentDispositionFilename: Option[String] =
response header "Content-Disposition" collect {
case ContentDispositionFilename(filename) =>
filename.replaceAll("[^a-zA-Z0-9.-_]", "")
}
def urlFilename(url: String): String =
java.net.URLDecoder.decode(url.split("/").last, "UTF-8")
def contentType: String =
response header "Content-Type" getOrElse "application/octet-stream"
}
}
示例14: 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))
}
}
示例15: createRelationship
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentfirelationship.support
import org.scalatest.Suite
import play.api.libs.ws.WSResponse
import play.api.mvc.Results
trait RelationshipActions extends ActionsSupport {
this: Suite =>
def createRelationship ( agentId: String, clientId: String, service: String ): WSResponse =
wsClient
.url(s"$url/agent/$agentId/service/$service/client/$clientId")
.put(Results.EmptyContent())
.futureValue
def getRelationship ( agentId: String, clientId: String, service: String ): WSResponse =
wsClient
.url(s"$url/agent/$agentId/service/$service/client/$clientId")
.get()
.futureValue
def deleteRelationship ( agentId: String, clientId: String, service: String ): WSResponse =
wsClient
.url(s"$url/agent/$agentId/service/$service/client/$clientId")
.delete()
.futureValue
}