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


Scala HttpEntity类代码示例

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


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

示例1: index

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._
import akka.util.ByteString
import play.api._
import play.api.mvc._
import play.api.http.HttpEntity


  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

  def myAction = Action { request =>
    val htmlResult2 = Ok(<h1>Hello World!</h1>).as(HTML)
//    Ok("Hello world")
    htmlResult2
  }

  def hello(name: String) = Action {
    Ok("Hello " + name)
  }

  def resultExample = Action {
    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Strict(ByteString("Hello world!"), Some("text/plain"))
    )
  }

  def todo(name:String) = TODO

  def showId(id:Long) = Action {
    Ok(s"You have id $id")
  }

  def save = Action(parse.json) { request =>
    Ok("Got: " + (request.body \ "name").as[String])
  }

} 
开发者ID:bradkarels,项目名称:strange-symbols,代码行数:42,代码来源:HomeController.scala

示例2: Router

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

import pokestats.UPickleSerializers.pickler
import javax.inject.Inject

import akka.util.ByteString
import play.api.{Configuration, Environment}
import play.api.http.HttpEntity
import play.api.mvc._
import pokestats.{Api, UPickleSerializers}

import scala.concurrent.ExecutionContext

object Router
    extends UPickleSerializers
    with autowire.Server[String, pickler.Reader, pickler.Writer]

class Application @Inject()(
    action: DefaultActionBuilder,
    parsers: PlayBodyParsers,
    api: Api)(
    implicit context: ExecutionContext,
    config: Configuration,
    env: Environment)
    extends InjectedController {

  def index(path: String) = action {
    Ok(views.html.pokestats.index("PokéStats"))
  }

  def autowireApi(path: String) = action.async(parsers.tolerantText) {
    implicit request =>
      println(s"Request path: $path")

      // get the request body as String
      val b = request.body

      // call Autowire route
      Router
        .route[Api](api)(
          autowire.Core
            .Request(path.split("/"), pickler.read[Map[String, String]](b))
        )
        .map(result => {
          Result(
            header = ResponseHeader(200, Map.empty),
            body =
              HttpEntity.Strict(ByteString(result), Some("application/json"))
          )
        })
  }
} 
开发者ID:guilgaly,项目名称:pokemon-stats,代码行数:53,代码来源:Application.scala

示例3: PjaxFilter

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

import javax.inject.Inject

import akka.stream.Materializer
import akka.util.ByteString
import com.thatscalaguy.utils.HTML
import play.api.http.HttpEntity
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}


class PjaxFilter @Inject()(materializer: Materializer)(implicit executionContext: ExecutionContext) extends Filter {
  private[this] val CONTAINER_KEY = "X-PJAX-Container"
  private[this] val PJAX_KEY = "X-PJAX"

  override implicit def mat: Materializer = materializer

  override def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    rh.headers.get(PJAX_KEY) match {
      case Some("true") if rh.headers.keys.contains(CONTAINER_KEY) =>
        f(rh) flatMap { result =>
          stripBody(result.body, rh.headers.get(CONTAINER_KEY).get.replace("#", "")) map { body =>
            result.copy(body = body)
          }
        }
      case _ => f(rh)
    }
  }

  private[this] def stripBody(body: HttpEntity, container: String): Future[HttpEntity] = {
    body.consumeData map { content =>
      val root = HTML.loadString(content.decodeString("UTF-8"))

      val stripedBody = (root \\ "_" filter (_ \@ "id" == container)).toString

      val newContent = if(stripedBody.isEmpty) content.decodeString("UTF-8") else stripedBody

      HttpEntity.Strict(ByteString(newContent), body.contentType)
    }
  }
} 
开发者ID:ThatScalaGuy,项目名称:play-pjax,代码行数:44,代码来源:PjaxFilter.scala

示例4: HomeController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import akka.stream.scaladsl.{FileIO, Source}
import akka.util.ByteString
import play.api.http.HttpEntity
import play.api.mvc._


@Singleton
class HomeController @Inject()(webJarAssets: WebJarAssets) extends Controller {

  def index = {
    Action {
      Ok(views.html.index("Your new application is ready.", webJarAssets))
    }
  }

  def streaming = {
    Action {
      val file = new java.io.File("conf/vid4.mp4")
      val path: java.nio.file.Path = file.toPath
      val source: Source[ByteString, _] = FileIO.fromPath(path)

      Result(
        header = ResponseHeader(200, Map.empty),
        body = HttpEntity.Streamed(source, Some(file.length), Some("application/mp4"))
      )

      
    }
  }
} 
开发者ID:rahulforallp,项目名称:playu,代码行数:35,代码来源:HomeController.scala

示例5: sendFile

//设置package包名称以及导入依赖的类
package services

import java.io.File
import java.nio.file.{Files, Path}

import akka.stream.scaladsl.FileIO
import play.api.http.{HeaderNames, HttpEntity, HttpProtocol, MimeTypes}
import play.api.mvc.{Request, ResponseHeader, Result, Results}


trait FileUploadingService {

  def sendFile(name: String, filePath: Path)(implicit request: Request[_]): Result = {
    val file = new File(filePath.toString)

    if (file.exists()) {
      val source = FileIO.fromPath(file.toPath)
      val contentType = Option(Files.probeContentType(filePath)).getOrElse(MimeTypes.BINARY)

      val headers = Seq(
        HeaderNames.CONTENT_DISPOSITION -> s"attachment; filename=$name",
        HeaderNames.CONTENT_TYPE -> contentType
      )

      request.version match {
        case HttpProtocol.HTTP_1_0 =>
          val size = file.length()
          val httpEntity = HttpEntity.Streamed(source, Some(size), Some(contentType))

          Result(
            header = ResponseHeader(200, Map(HeaderNames.CONTENT_LENGTH -> size.toString) ++ headers.toMap),
            body = httpEntity
          )
        case HttpProtocol.HTTP_1_1 =>
          Results.Ok.chunked(source).withHeaders(headers: _*)
      }
    } else {
      Results.NotFound
    }
  }

} 
开发者ID:yarosman,项目名称:captchanator,代码行数:43,代码来源:FileUploadingService.scala

示例6: Tweet

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

import java.util.concurrent.atomic.AtomicLong
import javax.inject.{Inject, Singleton}

import akka.util.ByteString
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.http.Status.OK
import play.api.http.{ContentTypes, HttpEntity}
import play.api.mvc._

import scala.concurrent.ExecutionContext

case class Tweet(id: Long, author: String, content: String)

@Singleton
class TweetService @Inject()() {
  val counter = new AtomicLong(1000000L)

  def list(): List[Tweet] = {
    List(
      Tweet(counter.getAndIncrement(), "author1", "Hello, World!")
    )
  }
}

@Singleton
class TweetApi @Inject()(tweetService: TweetService)
                        (implicit ec: ExecutionContext)
  extends Controller with JsonResults {

  def list() = Action { req =>
    JsonOk(tweetService.list())
  }
}

trait JsonResults {

  val mapper = new ObjectMapper()
    .registerModule(DefaultScalaModule)

  class JsonStatus(status: Int)
    extends Result(header = ResponseHeader(status), body = HttpEntity.NoEntity) {

    def apply[C](content: AnyRef): Result = {
      val header = ResponseHeader(status)
      val json = mapper.writeValueAsBytes(content)
      val body = HttpEntity.Strict(ByteString(json), Some(ContentTypes.JSON))
      Result(header, body)
    }
  }

  val JsonOk = new JsonStatus(OK)
} 
开发者ID:digitalstreamio,项目名称:webfx-bench,代码行数:56,代码来源:Boot.scala

示例7: StreamController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.mugglmenzel.iot.model.ReadingProtos
import models.Reading
import play.api.Logger
import play.api.data.Form
import play.api.data.Forms._
import play.api.http.{HttpChunk, HttpEntity}
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json.{Json, Writes}
import play.api.mvc._

import scala.concurrent.Future

@Singleton
class StreamController @Inject() extends Controller {

  implicit val readingWrites = new Writes[Reading] {
    def writes(reading: Reading) = Json.obj(
      "metricId" -> reading.metricId,
      "timestamp" -> reading.timestamp
    )
  }

  def source = Action { implicit request =>
    Form(single("produce" -> optional(number))).bindFromRequest().fold(error => BadRequest,
      produce =>
        Ok.sendEntity(HttpEntity.Chunked(Source(1 to produce.getOrElse(99)).map { i =>
          lazy val json = Json.toJson(Reading("metric1", i)).toString()
          Future {
            Logger.info("returning: " + json.length + " bytes, as String: " + json)
          }
          HttpChunk.Chunk(ByteString(json))
        }, Some(JSON)))
    )
  }

  def protobufSource = Action { implicit request =>
    Form(single("produce" -> optional(number))).bindFromRequest().fold(error => BadRequest,
      produce =>
        Ok.sendEntity(HttpEntity.Chunked(Source(1 to produce.getOrElse(99)).map { i =>
          lazy val proto = ReadingProtos.ReadingProto.newBuilder().setMetricId("metric1").setTimestamp(i).build()
          Future {
            Logger.info("returning: " + proto.getSerializedSize + " bytes, as String: " + proto.toByteString.toStringUtf8)
          }
          HttpChunk.Chunk(ByteString(proto.toByteArray))
        }, Some(TEXT)))
    )
  }

} 
开发者ID:mugglmenzel,项目名称:play-akka-streams-prosumer,代码行数:56,代码来源:StreamController.scala


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