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


Scala HttpEntity类代码示例

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


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

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

示例2: Implicits

//设置package包名称以及导入依赖的类
package io.$org$.service.$domain;format="lower"$.converter

import com.typesafe.scalalogging.LazyLogging
import io.$org$.domain.$domain;format="lower"$.$domain$
import io.$org$.domain.$domain;format="lower"$.$domain$._
import io.kyriakos.library.crud.Converter
import spray.http.HttpEntity
import spray.httpx.marshalling._
import spray.httpx.unmarshalling._

object Implicits {

  implicit object HttpEntityConverter extends Converter[$domain$, HttpEntity] with LazyLogging {

    override def serialise($domain;format="lower"$: $domain$): HttpEntity =
      marshal($domain;format="lower"$) match {
      case Right(httpEntity) =>
        logger debug s"serialised \$$domain;format="lower"$ into \$httpEntity"
        httpEntity
      case Left(throwable) => throw throwable
    }

    override def deserialise(httpEntity: HttpEntity): $domain$ =
      httpEntity.as[$domain$] match {
        case Right($domain;format="lower"$) =>
      logger debug s"deserialised \$httpEntity into \$$domain;format="lower"$"
      $domain;format="lower"$
        case Left(deserializationError) => throw new RuntimeException(
          s"error deserialising \$httpEntity into $domain;format="lower"$ (info:\$deserializationError)")
      }
  }


} 
开发者ID:edinhodzic,项目名称:kyriakos-rest-micro-service-spray.g8,代码行数:35,代码来源:Implicits.scala

示例3: printer

//设置package包名称以及导入依赖的类
package io.circe.spray

import cats.data.Validated
import io.circe.{ Errors, Printer, RootEncoder }
import io.circe.jawn._
import spray.http.{ ContentTypes, HttpCharsets, HttpEntity, MediaTypes }
import spray.httpx.marshalling.Marshaller
import spray.httpx.unmarshalling.Unmarshaller

trait JsonSupport {
  def printer: Printer

  implicit final def circeJsonMarshaller[A](implicit encoder: RootEncoder[A]): Marshaller[A] =
    Marshaller.delegate[A, String](ContentTypes.`application/json`) { value =>
      printer.pretty(encoder(value))
    }

  implicit def circeJsonUnmarshaller[A](implicit decoder: RootDecoder[A]): Unmarshaller[A]
}

trait FailFastUnmarshaller { this: JsonSupport =>
  implicit final def circeJsonUnmarshaller[A](implicit decoder: RootDecoder[A]): Unmarshaller[A] =
    Unmarshaller[A](MediaTypes.`application/json`) {
      case x: HttpEntity.NonEmpty =>
        decode[A](x.asString(defaultCharset = HttpCharsets.`UTF-8`))(decoder.underlying) match {
          case Right(a) => a
          case Left(e) => throw e
        }
    }
}

trait ErrorAccumulatingUnmarshaller { this: JsonSupport =>
  implicit final def circeJsonUnmarshaller[A](implicit decoder: RootDecoder[A]): Unmarshaller[A] =
    Unmarshaller[A](MediaTypes.`application/json`) {
      case x: HttpEntity.NonEmpty =>
        decodeAccumulating[A](x.asString(defaultCharset = HttpCharsets.`UTF-8`))(decoder.underlying) match {
          case Validated.Valid(result) => result
          case Validated.Invalid(errors) => throw Errors(errors)
        }
    }
}

trait NoSpacesPrinter { this: JsonSupport =>
  final def printer: Printer = Printer.noSpaces
}

final object JsonSupport extends JsonSupport with NoSpacesPrinter with FailFastUnmarshaller

final object ErrorAccumulatingJsonSupport extends JsonSupport with NoSpacesPrinter with ErrorAccumulatingUnmarshaller 
开发者ID:travisbrown,项目名称:circe-spray,代码行数:50,代码来源:JsonSupport.scala

示例4: MainSpec

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

import org.scalatest._
import spray.testkit.ScalatestRouteTest
import spray.http.HttpEntity
import spray.http.ContentTypes
import spray.can.server.Stats
import spray.http.StatusCodes._
import org.json4s._

class MainSpec extends FreeSpec with Matchers with ScalatestRouteTest with SpraySampleService {
  def actorRefFactory = system

  "The spraysample Route" - {
    "when listing entities" - {
      "returns a JSON list" in {
        //Mix in Json4s, but only for this test
        import Json4sProtocol._

        Get("/entity") ~> spraysampleRoute ~> check {
          assert(contentType.mediaType.isApplication)

          //Check content type
          contentType.toString should include("application/json")
          //Try serializaing as a List of Foo
          val response = responseAs[List[Foo]]

          response.size should equal(2)
          response(0).bar should equal("foo1")

          //Check http status
          status should equal(OK)
        }
      }
    }
    "when posting an entity" - {
      "gives a JSON response" in {
        // FIXME: Should be able to send entity as JObject
        Post("/entity", HttpEntity(ContentTypes.`application/json`, """{"bar": "woot!"}""")) ~> spraysampleRoute ~> check {
          responseAs[String] should include("\"I got a response: Ok")
          status should equal(Created)
        }
      }
    }
  }
} 
开发者ID:msfrms,项目名称:ScalaRedirectTest,代码行数:48,代码来源:BasicSampleSpec.scala

示例5: CrawlerMocksUtil

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

import org.specs2.mock.Mockito
import spray.http.{HttpEntity, _}
import test.UtilTest

import scala.concurrent.Future


object CrawlerMocksUtil {

  object HttpClientMock extends Mockito {
    val mockResponse = mock[HttpResponse]
    val mockStatus = mock[StatusCode]
    mockResponse.status returns mockStatus
    mockStatus.isSuccess returns true

    def mockResponseWithJson(jsonFileName: String) = {
      val jsonBytes = UtilTest.readResource(jsonFileName)
      val body = HttpEntity(ContentTypes.`application/json`, jsonBytes)
      mockResponse.entity returns body
    }

    def mockResponseWithGzip(gzipFileName: String) = {
      val gzipBytes = UtilTest.readResource(gzipFileName)
      val body = HttpEntity(ContentTypes.`application/octet-stream`, gzipBytes)
      mockResponse.entity returns body
    }

    val sendAndReceive = {
      (req: HttpRequest) => Future.successful(mockResponse)
    }
  }

} 
开发者ID:MeMpy,项目名称:wow-characters,代码行数:36,代码来源:CrawlerMocksUtil.scala


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