本文整理汇总了Scala中akka.http.scaladsl.model.HttpResponse类的典型用法代码示例。如果您正苦于以下问题:Scala HttpResponse类的具体用法?Scala HttpResponse怎么用?Scala HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: exportReply
//设置package包名称以及导入依赖的类
package com.github.norwae.ignifera
import java.io.StringWriter
import akka.http.scaladsl.model.{ContentType, HttpEntity, HttpResponse}
import akka.util.ByteString
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports
def exportReply: HttpResponse = {
val writer = new StringWriter
TextFormat.write004(writer, registry.metricFamilySamples())
val string = writer.toString
HttpResponse(entity = HttpEntity.Strict(HttpExport.contentType, ByteString(string)))
}
}
object HttpExport {
val contentType: ContentType = ContentType.parse(TextFormat.CONTENT_TYPE_004).right.get
}
示例2: MonitoringEndpointsSpec
//设置package包名称以及导入依赖的类
package org.danielwojda.obfuscator.functionaltests
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import org.danielwojda.obfuscator.functionaltests.dsl.AkkaImplicits
import org.danielwojda.obfuscator.functionaltests.dsl.HttpEntityImplicitConverters._
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, GivenWhenThen, Matchers}
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps
class MonitoringEndpointsSpec extends FlatSpec with Matchers with GivenWhenThen with ScalaFutures with AkkaImplicits {
override implicit val patienceConfig = PatienceConfig(timeout = 2 seconds)
implicit val timeout = Timeout(patienceConfig.timeout)
"Service" should "expose the 'status' endpoint which always returns OK" in {
When("a 'status' endpoint is called")
val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://localhost:8080/private/status"))
Then("Http status 200 and OK body is returned")
whenReady(responseFuture) { response =>
response.status shouldBe StatusCodes.OK
response.entity.asString shouldBe "OK"
}
}
}
示例3: StatisticDataFetcher
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import scala.concurrent.{ExecutionContext, Future}
class StatisticDataFetcher(implicit ec: ExecutionContext, system: ActorSystem, materializer: ActorMaterializer) extends AutoMarshaller {
val statisticsServiceUrl = {
val config = ConfigFactory.load()
config.getString("statisticsServiceUrl")
}
def getStatistics(): Future[List[StatisticData]] = {
implicit val serialization = this.serialization
implicit val formats = this.formats
val responseFuture: Future[HttpResponse] =
Http(system).singleRequest(HttpRequest(uri = statisticsServiceUrl))
responseFuture flatMap { response =>
Unmarshal(response.entity).to[StatisticsResponse] map { statisticsResponse =>
statisticsResponse.query.results.quote
}
}
}
}
示例4: UnMarshalling
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{HttpMethods, HttpRequest, HttpResponse, MessageEntity}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.{ActorMaterializer, Materializer}
import akka.util.ByteString
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import spray.json._
object UnMarshalling {
def main(args: Array[String]) {
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
//type FromStringUnmarshaller[T] = Unmarshaller[String, T]
val intFuture = Unmarshal("42").to[Int]
val int = Await.result(intFuture, 1.second)
println("int unmarshalling "+int)
//type FromStringUnmarshaller[T] = Unmarshaller[String, T]
val boolFuture = Unmarshal("off").to[Boolean]
val bool = Await.result(boolFuture, 1.second)
println("off unmarshalling "+bool)
//type ToEntityMarshaller[T] = Marshaller[T, MessageEntity]
val string = "Yeah"
val entityFuture = Marshal(string).to[MessageEntity]
val entity = Await.result(entityFuture, 1.second) // don't block in non-test code!
println(entity)
//type ToResponseMarshaller[T] = Marshaller[T, HttpResponse]
val errorMsg = "Not found, pal!"
val responseFuture = Marshal(404 -> errorMsg).to[HttpResponse]
val response = Await.result(responseFuture, 1.second)
println(response)
//type FromEntityUnmarshaller[T] = Unmarshaller[HttpEntity, T]
val jsonByteString = ByteString("""{"name":"Hello"}""")
val httpRequest = HttpRequest(HttpMethods.POST, entity = jsonByteString)
val jsonDataUnmarshalledFuture = Unmarshal(httpRequest).to[String]
val jsonDataUnmarshalled = Await.result(jsonDataUnmarshalledFuture, 1.second)
println(jsonDataUnmarshalled)
sys.terminate()
}
}
示例5: route
//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker
import akka.http.scaladsl.marshalling.{Marshal, ToEntityMarshaller}
import akka.http.scaladsl.model.{HttpHeader, HttpResponse, ResponseEntity, StatusCode}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.config.ConfigFactory
import com.ulasakdeniz.hakker.template.Render
import de.heikoseeberger.akkahttpcirce.CirceSupport._
import io.circe.{Encoder, Json}
import io.circe.syntax._
import scala.collection.immutable
import scala.concurrent.ExecutionContext
trait Controller extends Render {
override lazy val config = ConfigFactory.load()
val StatusCodes = akka.http.scaladsl.model.StatusCodes
def route: Route
def apply(): Route = {
get {
// render frontend files
pathPrefix("js") {
renderDir("js")
}
} ~ route
}
def send(statusCode: StatusCode): Route = complete(statusCode)
def send[T](statusCode: StatusCode, content: T, headers: immutable.Seq[HttpHeader] = Nil)(
implicit marshaller: ToEntityMarshaller[T],
ec: ExecutionContext): Route = {
val response = Marshal(content)
.to[ResponseEntity](marshaller, ec)
.map(entity => {
HttpResponse(statusCode, headers = headers).withEntity(entity)
})
complete(response)
}
def sendJson[T](statusCode: StatusCode, content: T)(implicit encoder: Encoder[T],
ec: ExecutionContext): Route = {
sendJson(statusCode, content.asJson)
}
def sendJson[T](content: T)(implicit encoder: Encoder[T], ec: ExecutionContext): Route = {
sendJson(StatusCodes.OK, content)
}
def sendJson(statusCode: StatusCode, json: Json)(implicit ec: ExecutionContext): Route = {
send(statusCode, Option(json.noSpaces))
}
}
示例6: HttpResponseUtil
//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker.ws
import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.scaladsl.Sink
import akka.util.ByteString
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}
package object http {
implicit final class HttpResponseUtil(responseF: Future[HttpResponse]) extends HttpClientApi {
val entityData: Future[ByteString] =
for {
response <- responseF
byteString <- {
val source = response.entity.dataBytes
source.runWith(Sink.head[ByteString])
}
} yield byteString
def mapStrict[T](f: HttpResponse => T): Future[T] =
for {
response <- responseF
byteString <- entityData
strictEntity = HttpEntity.Strict(response.entity.contentType, byteString)
} yield f(response.withEntity(strictEntity))
def entityAs[T](implicit unmarshaller: Unmarshaller[String, T]): Future[Try[T]] = {
val result = for {
byteString <- entityData
t <- unmarshaller(byteString.utf8String)
} yield Success(t)
result.recover {
case t: Throwable => Failure(t)
}
}
}
}
示例7: RegistryClient
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.protocol.registry
import scala.concurrent.{ ExecutionContext, Future }
import akka.actor.ActorSystem
import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse, RequestEntity }
import akka.stream.Materializer
import fommil.sjs.FamilyFormats._
class RegistryClient(baseUrl: String = "http://api.flowhub.io") extends SLF4JLogging {
def register(runtime: Runtime, token: String)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): Future[HttpResponse] = {
log.debug(s"PUT $baseUrl/runtimes/${runtime.id}")
Marshal(runtime).to[RequestEntity].flatMap { entity =>
Http().singleRequest(HttpRequest(
PUT,
s"$baseUrl/runtimes/${runtime.id}",
List(Authorization(OAuth2BearerToken(token))),
entity))
}
}
def unregister(runtimeId: String, token: String)(implicit system: ActorSystem, mat: Materializer): Future[HttpResponse] = {
log.debug(s"DELETE $baseUrl/runtimes/$runtimeId")
Http().singleRequest(HttpRequest(
DELETE,
s"$baseUrl/runtimes/$runtimeId",
List(Authorization(OAuth2BearerToken(token)))))
}
}
示例8: MonitoringServer
//设置package包名称以及导入依赖的类
package com.scalaio.http.monitoring
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes, Uri}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import com.typesafe.config.Config
import com.yammer.metrics.HealthChecks
import com.yammer.metrics.core.HealthCheckRegistry
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, Json}
import scala.util.{Failure, Success}
import scala.collection.convert.wrapAsScala._
object MonitoringServer {
lazy val logger = LoggerFactory.getLogger(getClass)
def handleHealthchecks(registry: HealthCheckRegistry): Route = {
path("health") {
get {
complete {
val checks = registry.runHealthChecks
val payload = JsArray(checks.map {
case (name, result) =>
Json.obj(
"name" -> name,
"healthy" -> result.isHealthy,
"message" -> result.getMessage
)
}.toSeq)
val status = if (checks.values().forall(_.isHealthy)) OK else InternalServerError
HttpResponse(entity = HttpEntity(`application/json`, Json.stringify(payload)), status = status)
}
}
}
}
def start(serverConfig: Config, registry: HealthCheckRegistry = HealthChecks.defaultRegistry())
(implicit system: ActorSystem, materializer: Materializer): Unit = {
val host = serverConfig.getString("host")
val port = serverConfig.getInt("port")
logger.info(s"Starting monitoring server at: $host:$port")
val routes = handleHealthchecks(registry) ~ redirect(Uri("/health"), StatusCodes.SeeOther)
import system.dispatcher
Http()
.bindAndHandle(routes, host, port).onComplete {
case Success(Http.ServerBinding(address)) =>
logger.info(s"Monitoring server started at :$address")
case Failure(t) =>
logger.error("Error while trying to start monitoring server", t)
}
}
}
示例9: HttpClientProvider
//设置package包名称以及导入依赖的类
package org.zalando.react.nakadi.client.providers
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager}
import akka.actor.ActorContext
import akka.http.scaladsl.Http.OutgoingConnection
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.settings.ClientConnectionSettings
import akka.http.scaladsl.{Http, HttpsConnectionContext}
import akka.stream.scaladsl.Flow
import scala.concurrent.Future
import scala.concurrent.duration._
class HttpClientProvider(actorContext: ActorContext,
server: String, port: Int,
isConnectionSSL: Boolean = false,
acceptAnyCertificate: Boolean = false,
connectionTimeout: FiniteDuration) {
val http = Http(actorContext.system)
private val settings = {
ClientConnectionSettings
.apply(actorContext.system)
.withConnectingTimeout(connectionTimeout)
.withIdleTimeout(Duration.Inf)
}
val connection: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = {
isConnectionSSL match {
case true =>
val sslContext = if (!acceptAnyCertificate) SSLContext.getDefault else {
val permissiveTrustManager: TrustManager = new X509TrustManager() {
override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
override def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
}
val ctx = SSLContext.getInstance("TLS")
ctx.init(Array.empty, Array(permissiveTrustManager), new SecureRandom())
ctx
}
http.outgoingConnectionHttps(server, port, new HttpsConnectionContext(sslContext), settings = settings)
case false =>
http.outgoingConnection(server, port, settings = settings)
}
}
}
示例10: NoAuthority
//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.directives.Credentials
import scala.concurrent.Future
import scala.util.Random
class NoAuthority extends Authority {
lazy val anonymous = new Random(1337L)
def ping: Future[HttpResponse] = Future.successful(HttpResponse(StatusCodes.OK))
def channelAccess(credentials: Credentials, channel_uuid: String): Future[Option[Long]] = {
Future.successful(Some(anonymous.nextLong))
}
def overlordAccess(credentials: Credentials): Future[Option[Long]] = {
Future.successful(Some(anonymous.nextLong))
}
}
示例11: addAccessControlHeaders
//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi.utils
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive0, Route}
import com.typesafe.config.ConfigFactory
trait CorsSupport {
lazy val allowedOriginHeader = {
val config = ConfigFactory.load()
val sAllowedOrigin = config.getString("cors.allowed-origin")
if (sAllowedOrigin == "*")
`Access-Control-Allow-Origin`.*
else
`Access-Control-Allow-Origin`(HttpOrigin(sAllowedOrigin))
}
private def addAccessControlHeaders: Directive0 = {
mapResponseHeaders { headers =>
allowedOriginHeader +:
`Access-Control-Allow-Credentials`(true) +:
`Access-Control-Allow-Headers`("Token", "Content-Type", "X-Requested-With") +:
headers
}
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(200).withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)
)
)
}
def corsHandler(r: Route) = addAccessControlHeaders {
preflightRequestHandler ~ r
}
}
示例12: Rejection
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.{ActorMaterializer, Materializer}
object Rejection {
def main(args: Array[String]) {
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
implicit def myRejectionHandler = RejectionHandler.newBuilder().handle{
case MissingCookieRejection(cookieName) =>
complete(HttpResponse(StatusCodes.BadRequest, entity = "No cookies, no service!!!"))
}.handleNotFound {
complete((StatusCodes.NotFound, "Not here!"))
}.result()
val route =
path("welcome"){
get{
complete {
"welcome to rest service"
}
}
} ~
path("demo"){
get{
complete {
"welcome to demonstration"
}
}
} ~
path("wrong"){
reject{
ValidationRejection("Invalid path", None)
}
}
Http().bindAndHandle(route, "localhost", 8090)
}
}
示例13: Failure
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import akka.stream.{ActorMaterializer, Materializer}
object Failure {
def main(args: Array[String]) {
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
implicit def myExceptionHandler = ExceptionHandler {
case _: ArithmeticException =>
complete(HttpResponse(StatusCodes.BadRequest, entity = "Bad numbers, bad result!!!"))
case e: Throwable => {
println(e.getMessage)
println(e.getStackTraceString)
complete(HttpResponse(StatusCodes.BadRequest, entity = e.getMessage))
}
}
val route =
path("welcome"){
get{
complete {
"welcome to rest service"
}
}
} ~
path("demo"){
get {
complete {
100/0
"welcome to demonstration"
}
}
}
Http().bindAndHandle(route, "localhost", 8090)
}
}
示例14: corsAllowOrigins
//设置package包名称以及导入依赖的类
package com.signalswarm
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{HttpHeader, HttpResponse}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Route, Directive0, MethodRejection, RejectionHandler}
trait CorsSupport {
protected def corsAllowOrigins: List[String]
protected def corsAllowedHeaders: List[String]
protected def corsAllowCredentials: Boolean
protected def optionsCorsHeaders: List[HttpHeader]
protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
.newBuilder().handle {
case MethodRejection(supported) =>
complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, supported) ::
allowOrigin ::
optionsCorsHeaders
))
}
.result()
private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value))
origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
else
None
def cors[T]: Directive0 = mapInnerRoute { route => context =>
((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
case (OPTIONS, Some(allowOrigin)) =>
handleRejections(corsRejectionHandler(allowOrigin)) {
respondWithHeaders(allowOrigin,
`Access-Control-Allow-Credentials`(corsAllowCredentials)) {
preflightRequestHandler ~ route
}
}
case (_, Some(allowOrigin)) =>
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route ~ preflightRequestHandler
}
case (_, _) =>
route
})(context)
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(200).withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE),
`Access-Control-Allow-Headers`(corsAllowedHeaders)
)
)
}
}
示例15: addAccessControlHeaders
//设置package包名称以及导入依赖的类
package utils
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ Directive0, Route }
import com.typesafe.config.ConfigFactory
trait CorsSupport {
lazy val allowedOriginHeader = {
val config = ConfigFactory.load()
val sAllowedOrigin = config.getString("cors.allowed-origin")
if (sAllowedOrigin == "*")
`Access-Control-Allow-Origin`.*
else
`Access-Control-Allow-Origin`(HttpOrigin(sAllowedOrigin))
}
private def addAccessControlHeaders: Directive0 = {
mapResponseHeaders { headers =>
allowedOriginHeader +:
`Access-Control-Allow-Credentials`(true) +:
`Access-Control-Allow-Headers`("Token", "Content-Type", "X-Requested-With") +:
headers
}
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(200).withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)
))
}
def corsHandler(r: Route) = addAccessControlHeaders {
preflightRequestHandler ~ r
}
}