当前位置: 首页>>代码示例>>Scala>>正文


Scala HttpEntity类代码示例

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


在下文中一共展示了HttpEntity类的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
} 
开发者ID:Norwae,项目名称:ignifera,代码行数:24,代码来源:HttpExport.scala

示例2: 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)
      }
    }
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:42,代码来源:package.scala

示例3: HttpExportSpec

//设置package包名称以及导入依赖的类
package com.github.norwae.ignifera

import akka.http.scaladsl.model.HttpEntity
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.{CollectorRegistry, Gauge}
import org.scalatest.matchers.{MatchResult, Matcher}
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration._

class HttpExportSpec extends FlatSpec with Matchers {
  "The http export object" should "include metrics provided by the collector" in {
    val export =  new HttpExport {
      override val registry: CollectorRegistry = new CollectorRegistry()
    }
    val gauge = Gauge.build("testgauge", "Test").register(export.registry)
    gauge.inc()
    val reply = export.exportReply

    val entity = reply.entity.asInstanceOf[HttpEntity.Strict]
    val string = entity.data.utf8String
    string should containSubstring("testgauge")
  }

  it should "have the correct content type" in {
    val reply = new HttpExport {}.exportReply
    reply.entity.contentType.value.toLowerCase shouldEqual TextFormat.CONTENT_TYPE_004.toLowerCase
  }
  it should "include the default metrics" in {
    val reply = new HttpExport {}.exportReply
    val entity = reply.entity.asInstanceOf[HttpEntity.Strict]
    val string = entity.data.utf8String
    string should containSubstring("process_cpu_seconds_total")
    string should containSubstring("jvm_classes_loaded")
  }

  private def containSubstring(expected: String) =
    Matcher[String](left => MatchResult(left.contains(expected), s"Contain $expected", s"not contain $expected"))
} 
开发者ID:Norwae,项目名称:ignifera,代码行数:40,代码来源:HttpExportSpec.scala

示例4: 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)
    }
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:61,代码来源:MonitoringServer.scala

示例5: PageToDownload

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.platform

import akka.http.scaladsl.model.{HttpEntity, StatusCode}
import org.joda.time.DateTime
import ru.fediq.scrapingkit.model.PageRef
import ru.fediq.scrapingkit.scraper.Scraped

case class PageToDownload(
  ref: PageRef
)

case class PageToEnqueue(
  ref: PageRef
)

case class DownloadedPage(
  ref: PageRef,
  time: DateTime,
  status: StatusCode,
  body: HttpEntity.Strict
)

case class ScrapedPage(
  page: DownloadedPage,
  entities: Seq[Scraped]
)

case class ProcessedPage(
  ref: PageRef
)

case class FailedPage(
  ref: PageRef,
  time: DateTime,
  reason: Option[String] = None,
  cause: Option[Throwable] = None
) 
开发者ID:fediq,项目名称:scraping-kit,代码行数:38,代码来源:entities.scala

示例6: FileUploadStream

//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, Multipart, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.stream.scaladsl.Framing
import akka.util.ByteString

import scala.concurrent.Future



object FileUploadStream extends BaseSpec{

  def main(args: Array[String]) {

    val route =
      extractRequestContext { ctx =>
        implicit val materializer = ctx.materializer
        implicit val ec = ctx.executionContext
 
        fileUpload("csv") {
          case (metadata, byteSource) =>
            val sumF: Future[Int] =
            // sum the numbers as they arrive so that we can
            byteSource.via(Framing.delimiter(ByteString("\n"), 1024))
              .mapConcat(_.utf8String.split(",").toVector)
              .map(_.toInt)
              .runFold(0) { (acc, n) => acc + n }
              onSuccess(sumF) { sum => complete(s"Sum: $sum") }
        }
      }

    //Test file upload stream
    val multipartForm =
      Multipart.FormData(Multipart.FormData.BodyPart.Strict(
        "csv",
        HttpEntity(ContentTypes.`text/plain(UTF-8)`, "2,3,5\n7,11,13,17,23\n29,31,37\n"),
        Map("filename" -> "primes.csv")))
 
    Post("/", multipartForm) ~> route ~> check {
      status shouldEqual StatusCodes.OK
      responseAs[String] shouldEqual "Sum: 178"
    }

    system.terminate()
  }

}
//File upload direct
//curl --form "[email protected]" http://<host>:<port> 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:51,代码来源:FileUploadStream.scala

示例7: UtilityServiceSlice

//设置package包名称以及导入依赖的类
package com.microworkflow.rest

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._

class UtilityServiceSlice {

  val routes: Route = {
    path("") {
      pathEnd {
        complete("here")
      }
    } ~ path("info") {
      get {
        complete(HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, buildinfo.BuildInfo.toJson)))
      }
    }
  }
} 
开发者ID:polymorphic,项目名称:akka-http-svc.g8,代码行数:21,代码来源:UtilityServiceSlice.scala

示例8: ImperativeRequestContext

//设置package包名称以及导入依赖的类
package org.cristal.api.helper

import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise


final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
  private implicit val ec = ctx.executionContext
  def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
  def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}

trait ApiHelper {

  def notImplementedResponse(msg: String = ""): StandardRoute =
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
      s"<h1>We plan to support this resource soon.</h1>"))

  def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
    val p = Promise[RouteResult]()
    inner(new ImperativeRequestContext(ctx, p))
    p.future
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala

示例9: postRequest

//设置package包名称以及导入依赖的类
package se.meldrum.machine

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Matchers, WordSpec}
import PostgresTestDb._
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpEntity, HttpMethods, HttpRequest, MediaTypes}
import akka.stream.ActorMaterializer
import akka.util.ByteString
import se.meldrum.machine.http.RestService
import slick.driver.PostgresDriver.api._

import scala.concurrent.ExecutionContext

trait BaseSpec extends WordSpec with Matchers with ScalatestRouteTest {
  dbProcess.getProcessId
  implicit val db = Database.forConfig("postgres-test")
  implicit val sys = ActorSystem("machine")
  implicit val ec = ExecutionContext
  implicit val mat = ActorMaterializer()
  val restService = new RestService()
  val route = restService.route

  def postRequest(path: String, json: ByteString): HttpRequest =
    HttpRequest(HttpMethods.POST,
      uri = path,
      entity = HttpEntity(MediaTypes.`application/json`, json)
    )


  def userJsonRequest(name: String, pass: String, email: String): ByteString =
    ByteString(
      s"""
       |{
       |    "name":"$name",
       |    "password":"$pass",
       |    "email":"$email"
       |}
        """.stripMargin)


  def createTestUsers(): Seq[HttpRequest] = {
    val userOne = userJsonRequest("testuser", "secret", "[email protected]")
    val userTwo = userJsonRequest("testuser2", "secret", "[email protected]")
    val userThree = userJsonRequest("testuser3", "secret", "[email protected]")

    val requests = Seq(
      postRequest("/v1/user/create", userOne),
      postRequest("/v1/user/create", userTwo),
      postRequest("/v1/user/create", userThree)
    )
    requests
  }
} 
开发者ID:Max-Meldrum,项目名称:machine,代码行数:56,代码来源:BaseSpec.scala

示例10: AppReturningChunking

//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document

import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn

object AppReturningChunking extends Directives {
  
  implicit val system = ActorSystem()
  implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
  implicit val mat = ActorMaterializer()

  def main(args: Array[String]): Unit = {
    val mongoClient = MongoClients.create()
    val coll = mongoClient.getDatabase("test").getCollection("resources")

    val route =
      path("resources") {
        get {
          complete(HttpEntity(ContentTypes.`application/json`, getData(coll)))
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }

  def getData(coll: MongoCollection[Document]): Source[ByteString, NotUsed] =
    Source.fromPublisher(coll.find())
      .map(_.toJson)
      .map(ByteString(_))
      .intersperse(ByteString("["), ByteString(","), ByteString("]"))

} 
开发者ID:michalbogacz,项目名称:http-streaming,代码行数:51,代码来源:AppReturningChunking.scala

示例11: ApiReturningList

//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document

import scala.concurrent.{ExecutionContextExecutor, Future}
import scala.io.StdIn

object ApiReturningList extends ServiceDirectives {

  implicit val system = ActorSystem()
  implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
  implicit val mat = ActorMaterializer()

  def main(args: Array[String]): Unit = {
    val mongoClient = MongoClients.create()
    val coll = mongoClient.getDatabase("test").getCollection("resources")

    val route =
      path("resources") {
        pageParams { pageParams =>
          get {
            complete(getData(coll, pageParams).map(HttpEntity(ContentTypes.`application/json`, _)))
          }
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }

  def getData(coll: MongoCollection[Document], pageParams: PageParams): Future[String] =
    Source.fromPublisher(coll.find().skip(pageParams.skip).limit(pageParams.limit))
      .map(_.toJson)
      .intersperse("[", ",", "]")
      .runFold("")((acc, e) ? acc + e)


} 
开发者ID:michalbogacz,项目名称:http-streaming,代码行数:51,代码来源:ApiReturningList.scala

示例12: WebServer

//设置package包名称以及导入依赖的类
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn
import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.model.ContentTypes
 
object WebServer {
  def main(args: Array[String]) {
 
    implicit val system = ActorSystem("my-system")
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher
 
    val route =
      path("hello") {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
        }
      }
 
    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
 
    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ ? system.terminate()) // and shutdown when done
  }
} 
开发者ID:Chehao,项目名称:Akkala,代码行数:33,代码来源:WebServer.scala

示例13: unmarshaller

//设置package包名称以及导入依赖的类
package com.github.bots4s.telegramkit.client

import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToEntityMarshaller}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, MediaTypes, Multipart}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}

import com.github.bots4s.telegramkit.marshalling.{BotMarshaller, BotUnmarshaller}
import com.github.bots4s.telegramkit.method.{BotApiRequest, BotApiRequestJson, BotApiRequestMultipart}
import com.github.bots4s.telegramkit.model._


private[client] trait HttpMarshalling { this: BotApiClient =>
  implicit def unmarshaller[T: Manifest](implicit um: BotUnmarshaller[T]): FromEntityUnmarshaller[T] = {
    Unmarshaller.stringUnmarshaller.map(body => um(body))
  }

  implicit def marshaller[T](implicit m: BotMarshaller[BotApiRequestJson[T]]): ToEntityMarshaller[BotApiRequest[T]] = {
    Marshaller.strict {
      case request: BotApiRequestJson[T] =>
        val content = m(request)
        Marshalling.Opaque(() => HttpEntity(ContentTypes.`application/json`, content))
      case request: BotApiRequestMultipart[T] =>
        def flatten(value: Any): Any = value match {
          case Some(x) => flatten(x)
          case e: Either[_, _] => flatten(e.fold(identity, identity))
          case _ => value
        }
        val fields = request.getClass.getDeclaredFields.iterator.zip(request.productIterator).map {
          case (k, v) => HttpMarshalling.snakeCase(k.getName) -> flatten(v)
        }.filterNot(_._2 == None)

        if (fields.isEmpty) {
          Marshalling.Opaque(() => HttpEntity.empty(ContentTypes.`application/octet-stream`))
        } else {
          val parts = fields map {
            case (k, v @ (_: String | _: Boolean | _: Long | _: Float)) =>
              Multipart.FormData.BodyPart(k, HttpEntity(v.toString))
            case (k, InputFile.InputFilePath(path)) =>
              Multipart.FormData.BodyPart.fromPath(k, MediaTypes.`application/octet-stream`, path)
            case (k, InputFile.InputFileData(filename, bs)) =>
              Multipart.FormData.BodyPart(k, HttpEntity(ContentTypes.`application/octet-stream`, bs), Map("filename" -> filename))
            case (k, other) =>
              log.warning(s"unexpected field in multipart request, $k: $other")
              Multipart.FormData.BodyPart(k, HttpEntity(""))
          }
          Marshalling.Opaque(() => Multipart.FormData(parts.toSeq: _*).toEntity())
        }
    }
  }
}

private[client] object HttpMarshalling {
  private val CapitalLetter = "[A-Z]".r
  def snakeCase(s: String): String =
    CapitalLetter.replaceAllIn(s, { "_" + _.group(0).toLowerCase })
} 
开发者ID:bots4s,项目名称:TelegramKit,代码行数:57,代码来源:HttpMarshalling.scala

示例14: ClientsServiceTest

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

import akka.http.scaladsl.model.{HttpEntity, MediaTypes}
import gateway.restapi.domain.ClientEnitity
import io.circe.generic.auto._
import org.scalatest.concurrent.ScalaFutures

class ClientsServiceTest extends BaseServiceTest with ScalaFutures {

  trait Context {
    val cleanUp = cleanContext
    val testClients = provisionClientsList(5)
    val route = httpService.clientsRouter.route
  }

  "Users service" should {

    "retrieve empty clients list" in new Context {
      cleanContext
      Get("/clients") ~> route ~> check {
        responseAs[Seq[ClientEnitity]].length should be(0)
      }
    }

    "retrieve clients list" in new Context {
      Get("/clients") ~> route ~> check {
        responseAs[Seq[ClientEnitity]].length should be(5)
      }
    }

    "retrieve client by id" in new Context {
      val testClient = testClients(4)
      Get(s"/clients/${testClient.id.get}") ~> route ~> check {
        responseAs[ClientEnitity] should be(testClient)
      }
    }

    "create a new client" in new Context {
      val newClientName = "Smith Test"
      val requestEntity = HttpEntity(MediaTypes.`application/json`, s"""{"name": "$newClientName"}""")
      Post("/clients/", requestEntity) ~> route ~> check {
        responseAs[ClientEnitity].name should be(newClientName)
      }
    }
  }
} 
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:47,代码来源:ClientsServiceTest.scala

示例15: WebServer

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.{complete, get, path}
import akka.stream.ActorMaterializer

import scala.io.StdIn

object WebServer extends App {
  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  // needed for the future flatMap/onComplete in the end
  implicit val executionContext = system.dispatcher

  val route =
    path("hello") {
      get {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
      }
    }

  val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
} 
开发者ID:hiroinamine,项目名称:akka-labs,代码行数:32,代码来源:WebServer.scala


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