本文整理汇总了Scala中play.api.http.HeaderNames类的典型用法代码示例。如果您正苦于以下问题:Scala HeaderNames类的具体用法?Scala HeaderNames怎么用?Scala HeaderNames使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HeaderNames类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: myPublicAddress
//设置package包名称以及导入依赖的类
package org.zalando.hutmann.spec
import org.scalatest.concurrent.PatienceConfiguration.Interval
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import org.scalatestplus.play.{ PlaySpec, PortNumber, WsScalaTestClient }
import play.api.Application
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.{ WSClient, WSResponse }
trait PlayUnitSpec extends PlaySpec with ScalaFutures with WsScalaTestClient {
def myPublicAddress(): String
implicit val portNumber: PortNumber
def callWs(testPaymentGatewayURL: String)(implicit app: Application): WSResponse = {
implicit val wSClient = app.injector.instanceOf[WSClient]
val callbackURL = s"http://${myPublicAddress()}/callback"
whenReady(
wsUrl(testPaymentGatewayURL)
.withQueryStringParameters("callbackURL" -> callbackURL)
.withHttpHeaders(HeaderNames.ACCEPT -> MimeTypes.TEXT)
.get(),
Interval(Span(10, Seconds))
) { result =>
result
}
}
}
示例2: CustomCORSFilter
//设置package包名称以及导入依赖的类
package filters
import javax.inject.{Inject, Singleton}
import akka.stream.Materializer
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result}
import play.filters.cors.CORSFilter
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class CustomCORSFilter @Inject()(corsFilter: CORSFilter)
(implicit override val mat: Materializer,
exec: ExecutionContext) extends Filter {
override def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
requestHeader.headers.get(HeaderNames.ORIGIN) match {
case (Some("null")) =>
val newHeaders = requestHeader.headers
.remove(HeaderNames.ORIGIN)
.add(HeaderNames.ORIGIN -> "http://file.url.local.null")
val mappedOrigin = requestHeader.copy(headers = newHeaders)
corsFilter(nextFilter)(mappedOrigin)
.map { result =>
result.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "null")
}
case _ => corsFilter(nextFilter)(requestHeader)
}
}
}
示例3: PlaySpecApplication
//设置package包名称以及导入依赖的类
package common
import org.scalatestplus.play.PlaySpec
import play.api.http.{ HeaderNames, HttpProtocol, HttpVerbs, Status }
import play.api.test._
class PlaySpecApplication extends PlaySpec
with PlayRunners
with HeaderNames
with Status
with HttpProtocol
with DefaultAwaitTimeout
with ResultExtractors
with Writeables
with RouteInvokers
with FutureAwaits
with HttpVerbs
示例4: MultipartFormDataWritable
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.nio.file.{ Files, Paths }
import akka.util.ByteString
import play.api.http.{ HeaderNames, Writeable }
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{ Codec, MultipartFormData }
object MultipartFormDataWritable {
val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
def formatDataParts(data: Map[String, Seq[String]]): ByteString = {
val dataParts = data.flatMap {
case (key, values) =>
values.map { value =>
val name = s""""$key""""
s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
}
}.mkString("")
val bytes: ByteString = Codec.utf_8.encode(dataParts)
bytes
}
def filePartHeader(file: FilePart[TemporaryFile]): ByteString = {
val name = s""""${file.key}""""
val filename = s""""${file.filename}""""
val contentType = file.contentType.map { ct =>
s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
}.getOrElse("")
Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
}
val singleton = Writeable[MultipartFormData[TemporaryFile]](
transform = { form: MultipartFormData[TemporaryFile] =>
formatDataParts(form.dataParts) ++
form.files.flatMap { file =>
val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
} ++
Codec.utf_8.encode(s"--$boundary--")
},
contentType = Some(s"multipart/form-data; boundary=$boundary")
)
}
示例5: ProxyResponse
//设置package包名称以及导入依赖的类
package services
import java.util.concurrent.TimeUnit
import play.api.http.HeaderNames
import play.api.libs.iteratee.Iteratee
import play.api.mvc.{Result, Results}
import scala.concurrent.Await
import scala.concurrent.duration.Duration
object ProxyResponse {
def apply(result: Result): ProxyResponse = {
val body = new String(contentAsBytes(result))
val httpMessage = HttpMessage(result.header.headers.mapValues(_.split(",").toList), Some( body))
new ProxyResponse(result.header.status, httpMessage)
}
private def contentAsBytes(result: Result): Array[Byte] = {
val eBytes = result.header.headers.get(HeaderNames.TRANSFER_ENCODING) match {
case Some("chunked") => result.body &> Results.dechunk
case _ => result.body
}
Await.result(eBytes |>>> Iteratee.consume[Array[Byte]](), Duration(1, TimeUnit.SECONDS))
}
}
case class ProxyResponse(status: Int = 200, httpMessage: HttpMessage = HttpMessage(Map.empty, None)) {
def simpleHeaderMap: Map[String, String] = {
httpMessage.headers.map {
case (k, v) => (k, v.mkString(","))
}
}
}
示例6: ControllerTest
//设置package包名称以及导入依赖的类
package play.api.mvc.hal
import org.scalatest.{ FunSuite, Matchers }
import play.api.http.{ HeaderNames, Status }
import play.api.libs.json.Json
import play.api.mvc.{ Controller, Result }
import play.api.test.{ DefaultAwaitTimeout, FakeRequest, ResultExtractors }
import scala.concurrent.Future
class ControllerTest extends FunSuite with Matchers with ResultExtractors with HeaderNames with Status with DefaultAwaitTimeout {
class TestController() extends Controller with HalWriteController
test("A HAL Resource should be writeable") {
val controller = new TestController()
val result: Future[Result] = controller.hal().apply(FakeRequest())
val bodyText: String = contentAsString(result)
contentType(result) should equal(Some("application/hal+json"))
(Json.parse(bodyText) \ "foo").as[String] should equal("bar")
}
test("A Resource can be retrived as JSON") {
val controller = new TestController()
val result: Future[Result] = controller.halOrJson.apply(FakeRequest().withHeaders("Accept" -> "application/json"))
contentType(result) should equal(Some("application/json"))
}
test("A Resource can be retrived as HAL") {
val controller = new TestController()
val result: Future[Result] = controller.halOrJson.apply(FakeRequest().withHeaders("Accept" -> "application/hal+json"))
contentType(result) should equal(Some("application/hal+json"))
}
}
示例7: RouteService
//设置package包名称以及导入依赖的类
package services
import javax.inject.Inject
import models.{Route, Vehicle}
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.http.HeaderNames
import play.api.http.ContentTypes
import scala.concurrent.{ExecutionContext, Future}
class RouteService @Inject() (ws: WSClient) {
private val BASE_URL = "http://m.cdsvyatka.com/tratata.php"
private val ROUTE_PARAM_NAME = "marsh"
private val REFERER = "http://m.cdsvyatka.com/mobile_map.php"
private def parseResponse(res: WSResponse): Seq[Vehicle] = {
res.json.validate[Map[String, Vehicle]].fold(_ => Seq.empty, _.values.toSeq)
}
def routeVehicles(route: Route)(implicit ec: ExecutionContext): Future[Seq[Vehicle]] = {
ws.url(BASE_URL)
.withQueryString(ROUTE_PARAM_NAME -> route.id.toString)
.withHeaders(HeaderNames.ACCEPT -> ContentTypes.JSON, HeaderNames.REFERER -> REFERER)
.get()
.map(parseResponse)
}
}
示例8: asResult
//设置package包名称以及导入依赖的类
package microtools.hateoas
import play.api.http.HeaderNames
import play.api.libs.json.{Json, Writes}
import play.api.mvc.{Result, Results}
trait BusinessResult {
def asResult: Result
}
object BusinessResult {
def ok[D](data: D, allowesActions: Seq[BusinessAction] = Seq.empty, etag: Option[String] = None)(
implicit linkBuilder: LinkBuilder,
writes: Writes[D]
): BusinessResult =
new BusinessResult {
override def asResult: Result = {
val headers = etag.map(HeaderNames.ETAG -> _).toSeq
Results
.Ok(JsonTransformers.addHAL(Json.toJson(data), allowesActions))
.withHeaders(headers: _*)
}
}
def created(selfAction: BusinessAction)(implicit linkBuilder: LinkBuilder): BusinessResult =
new BusinessResult {
override def asResult: Result = {
val headers = Seq(HeaderNames.LOCATION -> linkBuilder.actionLink(selfAction).href)
Results.Created.withHeaders(headers: _*)
}
}
def created[D](
selfAction: BusinessAction,
data: D,
allowesActions: Seq[BusinessAction] = Seq.empty
)(
implicit linkBuilder: LinkBuilder,
writes: Writes[D]
): BusinessResult =
new BusinessResult {
override def asResult: Result = {
val headers = Seq(HeaderNames.LOCATION -> linkBuilder.actionLink(selfAction).href)
Results
.Created(JsonTransformers.addHAL(Json.toJson(data), allowesActions))
.withHeaders(headers: _*)
}
}
def deleted(): BusinessResult =
new BusinessResult {
override def asResult: Result = Results.NoContent
}
}
示例9: WSClientWithFlow
//设置package包名称以及导入依赖的类
package microtools.ws
import microtools.models.{AuthRequestContext, ExtraHeaders, RequestContext, ServiceName}
import play.api.http.HeaderNames
import play.api.libs.ws.{WSClient, WSRequest}
class WSClientWithFlow(val underlying: WSClient) {
private[this] object ForwardProto extends Enumeration {
type Type = Value
val HTTP = Value("http")
val HTTPS = Value("https")
}
def url(rawUrl: String)(implicit ctx: RequestContext): WSRequest = {
val (url, forwardProto): (String, ForwardProto.Type) =
if (rawUrl.startsWith("https:"))
s"http:${rawUrl.drop(6)}" -> ForwardProto.HTTPS
else rawUrl -> ForwardProto.HTTP
underlying
.url(url)
.withHeaders(ExtraHeaders.FLOW_ID_HEADER -> ctx.flowId,
HeaderNames.X_FORWARDED_PROTO -> forwardProto.toString)
}
def urlWithAuthFromContext(rawUrl: String)(implicit ctx: AuthRequestContext): WSRequest = {
url(rawUrl)
.withHeaders(HeaderNames.AUTHORIZATION -> s"Bearer ${ctx.token}")
}
def urlWithServiceAuth(rawUrl: String)(implicit serviceName: ServiceName,
ctx: RequestContext): WSRequest = {
url(rawUrl)
.withHeaders(
ExtraHeaders.AUTH_SUBJECT_HEADER -> s"service/$serviceName"
)
}
}
示例10: basic644
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fileupload.support
import com.google.common.base.Charsets
import com.google.common.io.BaseEncoding
import org.scalatest.Suite
import play.api.http.HeaderNames
import play.api.libs.ws.WSResponse
import play.utils.UriEncoding
import uk.gov.hmrc.fileupload.{EnvelopeId, FileId, FileRefId}
trait FileActions extends ActionsSupport {
this: Suite =>
def basic644(s:String): String = {
BaseEncoding.base64().encode(s.getBytes(Charsets.UTF_8))
}
def urlEncode(fileId: FileId) = UriEncoding.encodePathSegment(fileId.value, "UTF-8")
def upload(data: Array[Byte], envelopeId: EnvelopeId, fileId: FileId, fileRefId: FileRefId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/$fileId/$fileRefId")
.withHeaders("Content-Type" -> "application/octet-stream")
.put(data)
.futureValue
def delete(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}")
.delete()
.futureValue
def download(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/content").withHeaders(HeaderNames.AUTHORIZATION -> ("Basic " + basic644("yuan:yaunspassword")))
.get()
.futureValue
def getFileMetadataFor(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/metadata")
.get()
.futureValue
def downloadEnvelope(envelopeId: EnvelopeId): WSResponse =
client
.url(s"$fileTransferUrl/envelopes/$envelopeId")
.get()
.futureValue
}
示例11: Mobile
//设置package包名称以及导入依赖的类
package lila.api
import org.joda.time.DateTime
import play.api.http.HeaderNames
import play.api.mvc.RequestHeader
import lila.common.ApiVersion
object Mobile {
object Api {
case class Old(
version: ApiVersion,
// date when a newer version was released
deprecatedAt: DateTime,
// date when the server stops accepting requests
unsupportedAt: DateTime
)
val currentVersion = ApiVersion(2)
val acceptedVersions: Set[ApiVersion] = Set(1, 2) map ApiVersion.apply
val oldVersions: List[Old] = List(
Old( // chat messages are html escaped
version = ApiVersion(1),
deprecatedAt = new DateTime("2016-08-13"),
unsupportedAt = new DateTime("2016-11-13")
)
)
private val PathPattern = """^.+/socket/v(\d+)$""".r
def requestVersion(req: RequestHeader): Option[ApiVersion] = {
val accepts = ~req.headers.get(HeaderNames.ACCEPT)
if (accepts contains "application/vnd.lichess.v2+json") Some(ApiVersion(2))
else if (accepts contains "application/vnd.lichess.v1+json") Some(ApiVersion(1))
else req.path match {
case PathPattern(version) => parseIntOption(version) map ApiVersion.apply
case _ => None
}
} filter acceptedVersions.contains
def requested(req: RequestHeader) = requestVersion(req).isDefined
}
}
示例12: fetch
//设置package包名称以及导入依赖的类
package service
import com.google.inject.Inject
import play.api.Logger
import play.api.http.HeaderNames
import play.api.i18n.Lang
import play.api.libs.json.{JsError, JsSuccess, Json, Reads}
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.mvc.{Cookie, Cookies}
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.control.NonFatal
trait WsConsumer {
def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang): Future[T]
}
class WsConsumerImpl @Inject()(ws: WSClient) extends WsConsumer {
val log = Logger("WsConsumer")
override def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang) =
ws.url(url).
withCookies(Cookie("PLAY_LANG", lang.language)).
withRequestTimeout(timeout).
get().flatMap { result =>
Json.fromJson(result.json) match {
case JsSuccess(s, _) =>
Future.successful(s)
case JsError(e) =>
val errors = JsError.toJson(e).fields.foldLeft("")((acc, next) => acc + next + "\n")
Future.failed(new RuntimeException(s"Failed to unmarshal:\n $errors"))
}
}.recoverWith {
case NonFatal(t) =>
log.warn(s"Failed to fetch '$url'")
Future.failed(new RuntimeException(t))
}
implicit class WithCookiesOps(requestHolder: WSRequest) {
def withCookies(cookies: Cookie*): WSRequest = {
val encoded = Cookies.encodeSetCookieHeader(cookies.toSeq)
requestHolder.withHttpHeaders(HeaderNames.COOKIE -> encoded)
}
}
}
示例13: TestComponents
//设置package包名称以及导入依赖的类
package tests
import com.malliina.play.http.{PlayUtils, Proxies}
import play.api.ApplicationLoader.Context
import play.api.http.{HeaderNames, Writeable}
import play.api.libs.json.Json
import play.api.mvc._
import play.api.routing.Router
import play.api.test.FakeRequest
import play.api.{BuiltInComponentsFromContext, Configuration}
class TestComponents(ctx: Context) extends BuiltInComponentsFromContext(ctx) {
import play.api.routing.sird._
override lazy val configuration: Configuration = ctx.initialConfiguration ++ Configuration(
"play.http.forwarded.version" -> "x-forwarded",
"play.http.forwarded.trustedProxies" -> List("0.0.0.0/0", "::/0")
)
override def router: Router = Router.from {
case GET(p"/") => securityCheck(_.secure)
case GET(p"/mod") => securityCheck(Proxies.isSecure)
}
def securityCheck(isSecure: RequestHeader => Boolean) = Action { req =>
Results.Ok(Json.obj(
"secure" -> isSecure(req),
"headers" -> PlayUtils.headersString(req))
)
}
}
class SiloTest extends AppSuite(new TestComponents(_)) {
import play.api.test.Helpers._
test("play says secure is false despite https in trusted proxy") {
assert(!makeReq("/"))
}
test("Proxies.isSecure says https") {
assert(makeReq("/mod"))
}
def makeReq(url: String) = {
val reqHeaders = Headers(
HeaderNames.X_FORWARDED_PROTO -> "https",
HeaderNames.X_FORWARDED_FOR -> "10.0.0.1"
)
val res = makeRequest(FakeRequest(GET, url, reqHeaders, AnyContentAsEmpty))
assert(res.header.status === 200)
val json = contentAsJson(fut(res))
(json \ "secure").as[Boolean]
}
def makeRequest[T: Writeable](req: Request[T]): Result =
await(route(app, req).get)
}
示例14: 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
}
}
}
示例15: ApiClient
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import domain.{Post, User}
import play.api.http.HeaderNames
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json.JsSuccess
import play.api.libs.ws.WSClient
import scala.concurrent.Future
@Singleton
class ApiClient @Inject() (wsClient: WSClient) {
val endpoint = "http://jsonplaceholder.typicode.com"
def getUser(userId: String): Future[Option[User]] = {
wsClient.url(s"$endpoint/users/$userId").withHeaders(HeaderNames.CONTENT_TYPE -> "application/json").get() map {
response =>
response.json.validate[User] match {
case result: JsSuccess[User] => {
result.asOpt
}
case _ => None
}
}
}
def getPosts(userId: String): Future[Option[Seq[Post]]] = {
wsClient.url(s"$endpoint/posts").withQueryString(("userId", userId)).withHeaders(HeaderNames.CONTENT_TYPE -> "application/json").get() map {
response => response.json.validate[Seq[Post]] match {
case result: JsSuccess[Seq[Post]] => {
result.asOpt
}
case _ => None
}
}
}
}