本文整理汇总了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])
}
}
示例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"))
)
})
}
}
示例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)
}
}
}
示例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"))
)
}
}
}
示例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
}
}
}
示例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)
}
示例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)))
)
}
}