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

Scala HttpRequest类代码示例

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

本文整理汇总了Scala中spray.http.HttpRequest的典型用法代码示例。如果您正苦于以下问题:Scala HttpRequest类的具体用法?Scala HttpRequest怎么用?Scala HttpRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HttpRequest类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: sending

//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.spray

import akka.actor.ActorSystem
import akka.io.IO
import spray.can.Http
import spray.http.{ HttpHeader, HttpRequest, RemoteAddress, Uri }
import spray.http.HttpHeaders.{ `Remote-Address`, `X-Forwarded-For` }
import spray.routing.{ Directive1, RequestContext, Route }


trait ProxySupport extends ClientIPDirectives {

  private def sending(f: RequestContext => HttpRequest)(implicit system: ActorSystem): Route = {
    val transport = IO(Http)(system)
    ctx => transport.tell(f(ctx), ctx.responder)
  }

  private def getHeaders(ip: Option[RemoteAddress], headers: List[HttpHeader] = Nil) = {
    // filter `Host` header
    val hs = headers.filterNot(header => header.is("host"))
    // add `X-Forwarded-For` header
    ip.fold(hs)(addForwardedFor(_, hs))
  }

  private def addForwardedFor(ip: RemoteAddress, headers: List[HttpHeader]): List[HttpHeader] = {
    headers match {
      case Nil =>
        // No `X-Forwarded-For` found in headers, so just add the new one
        `X-Forwarded-For`(ip) :: Nil

      case `X-Forwarded-For`(ips) :: tail =>
        `X-Forwarded-For`(ips :+ ip) :: tail

      case notForwardedFor :: tail =>
        notForwardedFor :: addForwardedFor(ip, tail)
    }
  }

  private val optionalRemoteAddress: Directive1[Option[RemoteAddress]] =
    headerValuePF { case `Remote-Address`(address) => Some(address) } | provide(None)

  def proxyTo(uri: Uri)(implicit system: ActorSystem): Route = {
    optionalRemoteAddress { ip =>
      sending(ctx => ctx.request.copy(
        uri = uri,
        headers = getHeaders(ip, ctx.request.headers)))
    }
  }

  def proxyToUnmatchedPath(uri: Uri)(implicit system: ActorSystem): Route = {
    optionalRemoteAddress { ip =>
      sending { ctx =>
        ctx.request.copy(
          uri = uri.withPath(uri.path.++(ctx.unmatchedPath)).withQuery(ctx.request.uri.query),
          headers = getHeaders(ip, ctx.request.headers))
      }
    }
  }
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:60,代码来源:ProxySupport.scala


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


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


示例4: WebSocketWorker

//设置package包名称以及导入依赖的类
package nestapp.websocketserver

import akka.actor.{ActorRef, ActorRefFactory}
import spray.can.websocket
import spray.can.websocket.FrameCommandFailed
import spray.can.websocket.frame.{BinaryFrame, TextFrame}
import spray.http.HttpRequest
import spray.routing.HttpServiceActor



class WebSocketWorker(val serverConnection: ActorRef) extends HttpServiceActor with websocket.WebSocketServerWorker {
  override def receive = handshaking orElse businessLogicNoUpgrade orElse closeLogic

  def businessLogic: Receive = {
    // just bounce frames back for Autobahn testsuite
    case [email protected](_: BinaryFrame | _: TextFrame) => sender() ! x
    case Push(msg) => send(TextFrame(msg))
    case x: FrameCommandFailed => log.error("frame command failed", x)
    case x: HttpRequest => // do something
  }

  def businessLogicNoUpgrade: Receive = {
    implicit val refFactory: ActorRefFactory = context
    runRoute {
      getFromResourceDirectory("webapp")
    }
  }
} 
开发者ID:rafaelkyrdan,项目名称:nest-app,代码行数:30,代码来源:WebSocketWorker.scala


示例5: RestService

//设置package包名称以及导入依赖的类
package greendash.dataplayer

import akka.actor.{Actor, ActorRef, Props}
import com.typesafe.config.ConfigFactory
import greendash.dataplayer.Clock.AdjustSpeed
import spray.can.Http
import spray.http.HttpMethods._
import spray.http.{HttpRequest, Uri, _}


class RestService(clock: ActorRef) extends Actor {

    val config = ConfigFactory.load()
    var speedFactor = config.getInt("speed.factor")

    override def receive: Receive = {

        // when a new connection comes in we register ourselves as the connection handler
        case _: Http.Connected => sender ! Http.Register(self)

        case HttpRequest(POST, Uri.Path("/speed"), _, entity: HttpEntity.NonEmpty, _) =>
            try {
                speedFactor = entity.asString.toInt
                sender ! HttpResponse(entity = "OK")
                clock ! AdjustSpeed(speedFactor)
            } catch {
                case e: Throwable =>
                    sender ! HttpResponse(entity = "NOK: " + e.getMessage)
            }

        case HttpRequest(GET, Uri.Path("/speed"), _, entity, _) =>
            sender ! HttpResponse(entity = speedFactor.toString)

        case HttpRequest(GET, Uri.Path("/sensorList"), _, entity: HttpEntity, _) =>
            val target = sender
            clock ! ForwardSensorList(target, entity)

        case HttpRequest(GET, Uri.Path("/state"), _, entity: HttpEntity, _) =>
            val target = sender
            clock ! ForwardState(target, entity)

    }
}

object RestService {
    def props(clock: ActorRef) = Props(new RestService(clock))
}

class ForwardHttpResponse(target: ActorRef, entity: HttpEntity) {
    def forward(answer: String) = target ! HttpResponse(entity = answer)
}

case class ForwardSensorList(target: ActorRef, entity: HttpEntity) extends ForwardHttpResponse(target, entity)
case class ForwardState(target: ActorRef, entity: HttpEntity) extends ForwardHttpResponse(target, entity) 
开发者ID:green-dash,项目名称:data-player,代码行数:55,代码来源:RestService.scala


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


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala ElasticClient类代码示例发布时间:2022-05-23
下一篇:
Scala TestSource类代码示例发布时间: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