• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala HttpResponse类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了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))
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:23,代码来源:RestResult.scala


示例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)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:19,代码来源:SprayHttpResponse.scala


示例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}
  }
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:30,代码来源:CORSSupport.scala


示例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)
    }
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:37,代码来源:PreviewHelpers.scala


示例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)
  }

} 
开发者ID:frankfarrell,项目名称:irelandweather,代码行数:44,代码来源:twitterapi.scala


示例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

  }
  }
} 
开发者ID:dbdev138,项目名称:DEV-FYP-AWS-Storage-Service,代码行数:34,代码来源:CORSSupport.scala


示例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

  }
  }
} 
开发者ID:hughlunt,项目名称:todospray,代码行数:35,代码来源:CorsSupport.scala


示例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

  }
  }
} 
开发者ID:microdg,项目名称:PROD-Geo-Tagging-Service,代码行数:42,代码来源:CORSSupport.scala


示例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")))
  }
} 
开发者ID:nicktylah,项目名称:spray-http,代码行数:24,代码来源:Boot.scala


示例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)))
    }
  }
} 
开发者ID:mwang633,项目名称:example-service,代码行数:47,代码来源:ExampleClient.scala


示例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)
    }
  }
} 
开发者ID:MeMpy,项目名称:wow-characters,代码行数:45,代码来源:WowGuildApiSpecs.scala



注:本文中的spray.http.HttpResponse类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Node类代码示例发布时间:2022-05-23
下一篇:
Scala Email类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap