本文整理汇总了Scala中spray.http.HttpResponse类的典型用法代码示例。如果您正苦于以下问题:Scala HttpResponse类的具体用法?Scala HttpResponse怎么用?Scala HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpResponse类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RestResult
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package integration.setup
import play.api.libs.json.{ JsValue, Json }
import spray.http.HttpResponse
import scala.concurrent.duration.Duration
import scala.concurrent.{ Await, Awaitable }
lazy val entityPrettyJsonString: String = Json.prettyPrint(entityJson)
}
object RestResult {
def apply(response: HttpResponse): RestResult[HttpResponse] = {
new RestResult[HttpResponse](() => response, response)
}
def await(responseFuture: Awaitable[HttpResponse], waitTime: Duration): RestResult[HttpResponse] = {
apply(Await.result(responseFuture, waitTime))
}
}
示例2: SprayHttpResponse
//设置package包名称以及导入依赖的类
package mesosphere.marathon.integration.setup
import play.api.libs.json.{ JsError, JsSuccess, Json, Reads }
import spray.http.HttpResponse
import scala.reflect.ClassTag
object SprayHttpResponse {
def read[T](implicit reads: Reads[T], classTag: ClassTag[T]): HttpResponse => RestResult[T] = responseResult.andThen { result =>
result.map(_ => Json.fromJson(result.entityJson)).map {
case JsSuccess(value, _) => value
case JsError(errors) =>
throw new IllegalArgumentException(
s"could not parse as $classTag:\n${Json.prettyPrint(result.entityJson)}\nErrors:\n${errors.mkString("\n")}")
}
}
def responseResult: HttpResponse => RestResult[HttpResponse] = response => RestResult(response)
}
示例3: CORSSupport
//设置package包名称以及导入依赖的类
package com.pacbio.common.services.utils
import spray.http.HttpMethods._
import spray.http.{HttpResponse, HttpMethod, HttpMethods, AllOrigins}
import spray.http.HttpHeaders.{`Access-Control-Allow-Methods`, `Access-Control-Max-Age`, `Access-Control-Allow-Headers`, `Access-Control-Allow-Origin`}
import spray.routing._
import spray.routing.directives.BasicDirectives
object CORSSupport extends BasicDirectives {
val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
val optionsCorsHeaders = List(
`Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent, Authorization"),
`Access-Control-Max-Age`(1728000))
val cors: Directive0 = mapRequestContext { ctx => ctx.withRouteResponseHandling {
//It is an option request for a resource that responds to some other method
case Rejected(rejections) if ctx.request.method.equals(HttpMethods.OPTIONS) && rejections.exists(_.isInstanceOf[MethodRejection]) =>
val allowedMethods: List[HttpMethod] =
rejections.filter(_.isInstanceOf[MethodRejection]).map(_.asInstanceOf[MethodRejection].supported)
ctx.complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, allowedMethods: _*) :: allowOriginHeader ::
optionsCorsHeaders
))
}.withHttpResponseHeadersMapped { headers => allowOriginHeader :: headers}
}
}
示例4: withRequest
//设置package包名称以及导入依赖的类
package im.actor.server.enrich
import akka.actor.ActorSystem
import akka.http.scaladsl.util.FastFuture
import im.actor.server.enrich.PreviewMaker.Failures._
import im.actor.server.enrich.PreviewMaker._
import spray.client.pipelining._
import spray.http.{ HttpEntity, HttpRequest, HttpResponse }
import scala.concurrent.Future
import scala.util.{ Failure, Success, Try }
trait PreviewHelpers {
protected implicit val system: ActorSystem
def withRequest(request: ? HttpRequest, randomId: Long)(f: HttpResponse ? PreviewResult)(implicit system: ActorSystem): Future[PreviewResult] = {
import system.dispatcher
val singleRequest: HttpRequest ? Future[HttpResponse] = sendReceive
Try(request) match {
case Success(v) ? singleRequest(v) map f recover { case e: Exception ? failedToMakePreview(randomId, e.getMessage) }
case Failure(_) ? FastFuture.successful(failedToMakePreview(randomId))
}
}
def downloadDefault(entity: HttpEntity.NonEmpty, fileName: Option[String], gp: GetPreview, maxSize: Long): PreviewResult = {
val mediaType = entity.contentType.mediaType
val contentLength = entity.data.length
(mediaType.isImage, contentLength) match {
case (true, length) if length <= maxSize ?
PreviewSuccess(entity.data.toByteArray, fileName, mediaType.value, gp.clientUserId, gp.peer, gp.randomId)
case (true, _) ? contentTooLong(gp.randomId)
case (false, _) ? notAnImage(gp.randomId)
}
}
}
示例5: TwitterApi
//设置package包名称以及导入依赖的类
package core
import akka.actor.{Actor, Props, ActorSystem}
import spray.can.Http
import spray.http._
import spray.http.HttpRequest
import spray.http.HttpResponse
import akka.io.IO
import scala.io.Source
class TwitterApi private(system: ActorSystem, port: Int, body: String) {
private class Service extends Actor {
def receive: Receive = {
case _: Http.Connected =>
sender ! Http.Register(self)
case HttpRequest(HttpMethods.POST, _, _, _, _) =>
sender ! ChunkedResponseStart(HttpResponse(StatusCodes.OK))
sender ! MessageChunk(body = body)
sender ! ChunkedMessageEnd()
}
}
private val service = system.actorOf(Props(new Service))
private val io = IO(Http)(system)
io ! Http.Bind(service, "localhost", port = port)
def stop(): Unit = {
io ! Http.Unbind
system.stop(service)
system.stop(io)
}
}
object TwitterApi {
def apply(port: Int)(implicit system: ActorSystem): TwitterApi = {
val body = Source.fromInputStream(getClass.getResourceAsStream("/tweet.json")).mkString
new TwitterApi(system, port, body)
}
}
示例6: cors
//设置package包名称以及导入依赖的类
package com.support
import spray.http.{HttpMethods, HttpMethod, HttpResponse, AllOrigins}
import spray.http.HttpHeaders._
import spray.http.HttpMethods._
import spray.routing._
// see also https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
trait CORSSupport {
this: HttpService =>
private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
private val optionsCorsHeaders = List(
`Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"),
`Access-Control-Max-Age`(1728000))
def cors[T]: Directive0 = mapRequestContext { ctx => ctx.withRouteResponseHandling({
//It is an option requeset for a resource that responds to some other method
case Rejected(x) if (ctx.request.method.equals(HttpMethods.OPTIONS) && !x.filter(_.isInstanceOf[MethodRejection]).isEmpty) => {
val allowedMethods: List[HttpMethod] = x.filter(_.isInstanceOf[MethodRejection]).map(rejection=> {
rejection.asInstanceOf[MethodRejection].supported
})
ctx.complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, allowedMethods :_*) :: allowOriginHeader ::
optionsCorsHeaders
))
}
}).withHttpResponseHeadersMapped { headers =>
allowOriginHeader :: headers
}
}
}
示例7: cors
//设置package包名称以及导入依赖的类
package com.example
import spray.http.{HttpMethods, HttpMethod, HttpResponse, AllOrigins}
import spray.http.HttpHeaders._
import spray.http.HttpMethods._
import spray.routing._
// see also https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
trait CORSSupport {
this: HttpService =>
private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
private val optionsCorsHeaders = List(
`Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"),
`Access-Control-Max-Age`(1728000))
def cors[T]: Directive0 = mapRequestContext { ctx => ctx.withRouteResponseHandling({
//It is an option requeset for a resource that responds to some other method
case Rejected(x) if (ctx.request.method.equals(HttpMethods.OPTIONS) && !x.filter(_.isInstanceOf[MethodRejection]).isEmpty) => {
val allowedMethods: List[HttpMethod] = x.filter(_.isInstanceOf[MethodRejection]).map(rejection=> {
rejection.asInstanceOf[MethodRejection].supported
})
ctx.complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, allowedMethods :_*) :: allowOriginHeader ::
optionsCorsHeaders
))
}
}).withHttpResponseHeadersMapped { headers =>
allowOriginHeader :: headers
}
}
}
示例8: cors
//设置package包名称以及导入依赖的类
//Please note the following code is not my own work.
//It is the reuse of work which is publicly available on Github
//The purpose of the below Trait is to provide a custom directive for Cross Origin Resource Sharing
package com.support
import spray.http.{HttpMethods, HttpMethod, HttpResponse, AllOrigins}
import spray.http.HttpHeaders._
import spray.http.HttpMethods._
import spray.routing._
// see also https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
trait CORSSupport {
this: HttpService =>
private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
private val optionsCorsHeaders = List(
`Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"),
`Access-Control-Max-Age`(1728000))
def cors[T]: Directive0 = mapRequestContext { ctx => ctx.withRouteResponseHandling({
//It is an option requeset for a resource that responds to some other method
case Rejected(x) if (ctx.request.method.equals(HttpMethods.OPTIONS) && !x.filter(_.isInstanceOf[MethodRejection]).isEmpty) => {
val allowedMethods: List[HttpMethod] = x.filter(_.isInstanceOf[MethodRejection]).map(rejection=> {
rejection.asInstanceOf[MethodRejection].supported
})
ctx.complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, allowedMethods :_*) :: allowOriginHeader ::
optionsCorsHeaders
))
}
}).withHttpResponseHeadersMapped { headers =>
allowOriginHeader :: headers
}
}
}
示例9: Main
//设置package包名称以及导入依赖的类
package com.goguardian.http.spray
import akka.actor.{Actor, ActorSystem, Props}
import akka.io.IO
import spray.can.Http
import spray.http.{HttpRequest, HttpResponse}
import spray.http.HttpHeaders.Connection
object Main extends App {
implicit val system: ActorSystem = ActorSystem()
val boot = system.actorOf(Props(classOf[Boot]))
}
class Boot extends Actor {
import context.system
IO(Http) ! Http.Bind(self, interface = "0.0.0.0", port = 80)
def receive = {
case _: Http.Connected => sender ! Http.Register(self)
case _: HttpRequest => sender ! HttpResponse(headers = List(`Connection`("keep-alive")))
}
}
示例10: ExampleResponse
//设置package包名称以及导入依赖的类
package com.example.service
import akka.actor.ActorRefFactory
import org.apache.logging.log4j.LogManager
import spray.client.pipelining._
import spray.http.{FormData, HttpRequest, HttpResponse}
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol
import scala.concurrent.Future
case class ExampleResponse(id : String, name : String)
class ExampleClient(config : Configuration, implicit val system: ActorRefFactory) {
private object JsonProtocol extends DefaultJsonProtocol {
implicit val exampleResponseFormat = jsonFormat2(ExampleResponse)
}
import JsonProtocol._
import system.dispatcher
private val log = LogManager.getLogger(this.getClass)
private val logRequest: HttpRequest => HttpRequest = { r =>
log.debug(r.toString)
log.trace(r.entity.data.asString)
r
}
private val logResponse: HttpResponse => HttpResponse = { r =>
log.debug(r.toString)
log.trace(r.entity.data.asString)
r
}
private val jsonQuery = addHeader("Accept", "application/json") ~> logRequest ~> sendReceive ~> logResponse
def requestFuture(id : String) : Future[ExampleResponse] = {
val pipeline = jsonQuery ~> unmarshal[ExampleResponse]
pipeline {
Get(s"${config.ExampleRemoteServer.url}/getUser", FormData(Seq("id" -> id)))
}
}
}
示例11: WowGuildApiSpecs
//设置package包名称以及导入依赖的类
package test.crawler
import org.specs2.mutable.Specification
import spray.http.HttpResponse
import test.crawler.CrawlerMocksUtil.HttpClientMock
import test.crawler.CrawlerMocksUtil.HttpClientMock._
import wow.crawler.WowGuildApi
import wow.dto.WowGuild
import scala.concurrent.Await
import scala.concurrent.duration._
class WowGuildApiSpecs extends Specification{
val client = new WowGuildApi {
override def sendAndReceive = HttpClientMock.sendAndReceive
}
"A request to wowProgress data export" should {
"return an HttpResponse containing a gzip file" >> {
mockResponseWithGzip("eu_magtheridon_tier18.json.gz")
val futureResp = client.getGuildInfoFromWowProgress()
val res = Await.result(futureResp, 10 seconds)
res must beAnInstanceOf[HttpResponse]
//TODO imporve assert
}
}
"A request to blizzard guild api " should {
"return an object of type WowGuild with members" >> {
mockResponseWithJson("WowGuildMembers.json")
val futureResp = client.getGuildMembers("Mock")
val res = Await.result(futureResp, 10 seconds)
res must beAnInstanceOf[WowGuild]
res.members must beSome
val members = res.members.get
members must have size(633)
}
}
}