Packages

  • package root

    Provided herein is API documentation for Scamper, the HTTP library for Scala.

    Provided herein is API documentation for Scamper, the HTTP library for Scala.

    Definition Classes
    root
  • package scamper

    Defines core types.

    Defines core types.

    HTTP Messages

    At the core of Scamper is HttpMessage, which is a trait that defines the fundamental characteristics of an HTTP message. HttpRequest and HttpResponse extend the specification to define characteristics specific to their respective message types.

    An HttpRequest is created using a factory method defined in its companion object. Or you can start with a RequestMethod and use builder methods to further define the request.

    import scamper.Header
    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    
    val request = Get("/motd").setHeaders(
      Header("Host: localhost:8080"),
      Header("Accept: text/plain")
    )
    
    printf("Request Method: %s%n", request.method)
    printf("Target URI: %s%n", request.target)
    
    request.headers.foreach(println)
    
    val host: Option[String] = request.getHeaderValue("Host")

    An HttpResponse is created using a factory method defined in its companion object. Or you can start with a ResponseStatus and use builder methods to further define the response.

    import scamper.{ BodyParser, Header }
    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.Ok
    
    val response = Ok("There is an answer.").setHeaders(
      Header("Content-Type: text/plain"),
      Header("Connection: close")
    )
    
    printf("Status Code: %s%n", response.statusCode)
    printf("Reason Phrase: %s%n", response.reasonPhrase)
    
    response.headers.foreach(println)
    
    val contentType: Option[String] = response.getHeaderValue("Content-Type")
    
    implicit val parser = BodyParser.text()
    
    printf("Body: %s%n", response.as[String])
    Definition Classes
    root
  • package auth

    Provides specialized access to authentication headers.

    Provides specialized access to authentication headers.

    Challenges and Credentials

    When working with authentication, a Challenge is presented in the response, and Credentials in the request. Each of these has an assigned scheme, which is associated with either a token or a set of parameters.

    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.ResponseStatus.Registry.Unauthorized
    import scamper.auth.{ Authorization, Challenge, Credentials, WwwAuthenticate }
    
    // Present response challenge (scheme and parameters)
    val challenge = Challenge("Bearer", "realm" -> "developer")
    val res = Unauthorized().setWwwAuthenticate(challenge)
    
    // Present request credentials (scheme and token)
    val credentials = Credentials("Bearer", "QWxsIEFjY2VzcyEhIQo=")
    val req = Get("/dev/projects").setAuthorization(credentials)
    Basic Authentication

    There are subclasses defined for Basic authentication: BasicChallenge and BasicCredentials.

    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.ResponseStatus.Registry.Unauthorized
    import scamper.auth.{ Authorization, BasicChallenge, BasicCredentials, WwwAuthenticate }
    
    // Provide realm and optional parameters
    val challenge = BasicChallenge("admin", "title" -> "Admin Console")
    val res = Unauthorized().setWwwAuthenticate(challenge)
    
    // Provide user and password
    val credentials = BasicCredentials("sa", "l3tm31n")
    val req = Get("/admin/users").setAuthorization(credentials)

    In addition, there are methods for Basic authentication defined in the header classes.

    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.ResponseStatus.Registry.Unauthorized
    import scamper.auth.{ Authorization, WwwAuthenticate }
    
    // Provide realm and optional parameters
    val res = Unauthorized().setBasic("admin", "title" -> "Admin Console")
    
    // Access basic auth in response
    printf(s"Realm: %s%n", res.basic.realm)
    printf(s"Title: %s%n", res.basic.params("title"))
    
    // Provide user and password
    val req = Get("/admin/users").setBasic("sa", "l3tm3m1n")
    
    // Access basic auth in request
    printf(s"User: %s%n", req.basic.user)
    printf(s"Password: %s%n", req.basic.password)
    Bearer Authentication

    There are subclasses defined for Bearer authentication: BearerChallenge and BearerCredentials. In addition, there are Bearer-specific methods available in the header classes.

    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.ResponseStatus.Registry.Unauthorized
    import scamper.auth.{ Authorization, WwwAuthenticate }
    
    // Provide challenge parameters
    val res = Unauthorized().setBearer(
      "scope" -> "user profile",
      "error" -> "invalid_token",
      "error_description" -> "Expired access token"
    )
    
    // Print optional realm parameter
    res.bearer.realm.foreach(println)
    
    // Print scope from space-delimited parameter
    val scope: Seq[String] = res.bearer.scope
    scope.foreach(println)
    
    // Print error parameters
    res.bearer.error.foreach(println)
    res.bearer.errorDescription.foreach(println)
    res.bearer.errorUri.foreach(println)
    
    // Test for error conditions
    println(res.bearer.isInvalidToken)
    println(res.bearer.isInvalidRequest)
    println(res.bearer.isInsufficientScope)
    
    // Create request with Bearer token
    val req = Get("/users").setBearer("R290IDUgb24gaXQhCg==")
    
    // Access bearer auth in request
    printf("Token: %s%n", req.bearer.token)
    Definition Classes
    scamper
  • package client

    Provides HTTP client implementation.

    Provides HTTP client implementation.

    Using HTTP Client

    The HttpClient object can be used to send a request and handle the response.

    import scamper.BodyParser
    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.client.HttpClient
    
    implicit val parser = BodyParser.text()
    
    def getMessageOfTheDay(): Either[Int, String] = {
      val req = Get("localhost:8080/motd")
    
      // Send request and handle response
      HttpClient.send(req) { res =>
        res.isSuccessful match {
          case true  => Right(res.as[String])
          case false => Left(res.statusCode)
        }
      }
    }

    Note the request must be created with an absolute URI to make effective use of the client.

    Creating HTTP Client

    When using the HttpClient object as the client, it creates an HttpClient instance for one-time usage. If you plan to send multiple requests, you can create and maintain a reference to a client. With it, you also get access to methods corresponding to standard HTTP request methods.

    import scamper.BodyParser
    import scamper.Implicits.stringToUri
    import scamper.client.HttpClient
    
    implicit val parser = BodyParser.text()
    
    // Create HttpClient instance
    val client = HttpClient()
    
    def getMessageOfTheDay(): Either[Int, String] = {
      // Use client instance
      client.get("http://localhost:8080/motd") { res =>
        res.isSuccessful match {
          case true  => Right(res.as[String])
          case false => Left(res.statusCode)
        }
      }
    }

    And, if an implicit client is in scope, you can make use of send() on the request itself.

    import scamper.BodyParser
    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.client.HttpClient
    import scamper.client.Implicits.ClientHttpRequestType // Adds send method to request
    import scamper.headers.{ Accept, AcceptLanguage }
    import scamper.types.Implicits.{ stringToMediaRange, stringToLanguageRange }
    
    implicit val client = HttpClient()
    implicit val parser = BodyParser.text(4096)
    
    Get("http://localhost:8080/motd")
      .setAccept("text/plain")
      .setAcceptLanguage("en-US; q=0.6", "fr-CA; q=0.4")
      .send(res => println(res.as[String])) // Send request and print response

    See also ClientSettings for information about configuring the HTTP client before it is created.

    Definition Classes
    scamper
  • package cookies

    Provides specialized access to message cookies.

    Provides specialized access to message cookies.

    Request Cookies

    In HttpRequest, cookies are stringed together in the Cookie header. You can access them using extension methods provided by RequestCookies, with each cookie represented as PlainCookie.

    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.cookies.{ PlainCookie, RequestCookies }
    
    // Build request with cookies
    val req = Get("https://localhost:8080/motd").setCookies(
      PlainCookie("ID", "bG9zCg"), PlainCookie("Region", "SE-US")
    )
    
    // Print all cookies
    req.cookies.foreach(println)
    
    // Get cookies by name
    val id: Option[PlainCookie] = req.getCookie("ID")
    val region: Option[PlainCookie] = req.getCookie("Region")
    
    // Get cookie values by name
    assert(req.getCookieValue("ID").contains("bG9zCg"))
    assert(req.getCookieValue("Region").contains("SE-US"))
    Response Cookies

    In HttpResponse, the cookies are a collection of Set-Cookie header values. Specialized access is provided by ResponseCookies, with each cookie represented as SetCookie.

    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.Ok
    import scamper.cookies.{ ResponseCookies, SetCookie }
    
    // Build response with cookies
    val res = Ok("There is an answer.").setCookies(
      SetCookie("ID", "bG9zCg", path = Some("/motd"), secure = true),
      SetCookie("Region", "SE-US")
    )
    
    // Print all cookies
    res.cookies.foreach(println)
    
    // Get cookies by name
    val id: Option[SetCookie] = res.getCookie("ID")
    val region: Option[SetCookie] = res.getCookie("Region")
    
    // Get attributes of ID cookie
    val path: String = id.flatMap(_.path).getOrElse("/")
    val secure: Boolean = id.map(_.secure).getOrElse(false)
    
    // Get cookie values by name
    assert(res.getCookieValue("ID").contains("bG9zCg"))
    assert(res.getCookieValue("Region").contains("SE-US"))
    Definition Classes
    scamper
  • package headers

    Provides specialized access to message headers.

    Provides specialized access to message headers.

    Using Header Classes

    Specialized header access is provided by type classes. Some headers are available to both requests and responses, and others are available only to a specific message type. This behavior is driven by the HTTP specification.

    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    import scamper.headers.{ Accept, Host }
    import scamper.types.Implicits.stringToMediaRange
    
    // Build request using 'Host' and 'Accept' headers
    val req = Get("/motd")
      .setHost("localhost:8080")
      .setAccept("text/plain")
    
    // Access and print header values
    printf("Host: %s%n", req.host)
    printf("Accept: %s%n", req.accept.mkString(", "))
    Definition Classes
    scamper
  • package logging

    Provides logging facilities.

    Provides logging facilities.

    Definition Classes
    scamper
  • package server

    Provides HTTP server implementation.

    Provides HTTP server implementation.

    Building HTTP Server

    To build a server, you begin with ServerApplication. This is a mutable structure to which you apply changes to configure the server. Once the desired settings are applied, you invoke one of several methods to create the server.

    import java.io.File
    import scamper.BodyParser
    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.{ NotFound, Ok }
    import scamper.server.HttpServer
    import scamper.server.Implicits._
    
    // Get server application
    val app = HttpServer.app()
    
    // Add request handler to log all requests
    app.incoming { req =>
      println(req.startLine)
      req
    }
    
    // Add request handler to specific request method and path
    app.get("/about") { req =>
      Ok("This server is powered by Scamper.")
    }
    
    // Add request handler using path parameter
    app.put("/data/:id") { req =>
      def update(id: Int, data: String): Boolean = ???
    
      implicit val parser = BodyParser.text()
    
      // Get path parameter
      val id = req.params.getInt("id")
    
      update(id, req.as[String]) match {
        case true  => Ok()
        case false => NotFound()
      }
    }
    
    // Serve static files
    app.files("/main", new File("/path/to/public"))
    
    // Gzip response body if not empty
    app.outgoing { res =>
      res.body.isKnownEmpty match {
        case true  => res
        case false => res.setGzipContentEncoding()
      }
    }
    
    // Create server
    val server = app.create(8080)
    
    printf("Host: %s%n", server.host)
    printf("Port: %d%n", server.port)
    
    // Run server for 60 seconds
    Thread.sleep(60 * 1000)
    
    // Close server when done
    server.close()
    Definition Classes
    scamper
  • package types

    Defines standard types for header values.

    Defines standard types for header values.

    import scamper.Implicits.{ stringToEntity, stringToUri }
    import scamper.RequestMethod.Registry.Get
    import scamper.ResponseStatus.Registry.Ok
    import scamper.headers.{ Accept, ContentType, TransferEncoding }
    import scamper.types.{ MediaRange, MediaType, TransferCoding }
    
    val json = MediaRange("application", "json", 0.9f)
    val html = MediaRange("text/html; q=0.1")
    
    val req = Get("/motd")
      .setAccept(json, html)
    
    val text = MediaType("text/plain")
    val gzip = TransferCoding("gzip")
    
    val res = Ok("There is an answer.")
      .setContentType(text)
      .setTransferEncoding(gzip)

    Using values defined in Implicits, properly formatted strings can be implicitly converted to standardized types.

    import scamper.Implicits.{ stringToEntity, stringToUri }
    import scamper.RequestMethod.Registry.Get
    import scamper.ResponseStatus.Registry.Ok
    import scamper.headers.{ Accept, ContentType, TransferEncoding }
    import scamper.types.Implicits._
    
    val req = Get("/motd")
      .setAccept("application/json; q=0.9", "text/html; q=0.1")
    
    val res = Ok("There is an answer.")
      .setContentType("text/plain")
      .setTransferEncoding("gzip")
    Definition Classes
    scamper
    See also

    scamper.headers

  • package websocket

    Provides WebSocket implementation.

    Provides WebSocket implementation.

    Definition Classes
    scamper
  • BodyDecoder
  • BodyParser
  • Entity
  • EntityTooLarge
  • FilePart
  • Header
  • HeaderNotFound
  • HttpException
  • HttpMessage
  • HttpRequest
  • HttpResponse
  • HttpVersion
  • Implicits
  • MessageBuilder
  • Multipart
  • Part
  • QueryString
  • ReadLimitExceeded
  • RequestLine
  • RequestMethod
  • ResponseStatus
  • StartLine
  • StatusLine
  • TextPart
  • Uri

trait HttpResponse extends HttpMessage with MessageBuilder[HttpResponse]

Defines HTTP response.

See also

HttpRequest

Linear Supertypes
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. HttpResponse
  2. MessageBuilder
  3. HttpMessage
  4. AnyRef
  5. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Type Members

  1. type LineType = StatusLine

    Type of start line in message

    Type of start line in message

    Definition Classes
    HttpResponseHttpMessage

Abstract Value Members

  1. abstract def attributes: Map[String, Any]

    Gets message attributes.

    Gets message attributes.

    Definition Classes
    HttpMessage
    Note

    Attributes are arbitrary values associated with message and are not part of transmitted message.

  2. abstract def body: Entity

    Gets message body.

    Gets message body.

    Definition Classes
    HttpMessage
  3. abstract def headers: Seq[Header]

    Gets message headers.

    Gets message headers.

    Definition Classes
    HttpMessage
  4. abstract def setAttributes(attributes: Map[String, Any]): HttpResponse

    Creates message with supplied attributes.

    Creates message with supplied attributes.

    attributes

    message attributes

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    All previous attributes are removed.

  5. abstract def setBody(body: Entity): HttpResponse

    Creates message with supplied body.

    Creates message with supplied body.

    body

    message body

    returns

    new message

    Definition Classes
    MessageBuilder
  6. abstract def setHeaders(headers: Seq[Header]): HttpResponse

    Creates message with supplied headers.

    Creates message with supplied headers.

    headers

    message headers

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    All previous headers are removed.

  7. abstract def setStartLine(startLine: LineType): HttpResponse

    Creates message with supplied start line.

    Creates message with supplied start line.

    startLine

    message start line

    returns

    new message

    Definition Classes
    MessageBuilder
  8. abstract def startLine: LineType

    Gets message start line.

    Gets message start line.

    Definition Classes
    HttpMessage

Concrete Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##(): Int
    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  4. def addHeaders(one: Header, more: Header*): HttpResponse

    Creates message with additional headers.

    Creates message with additional headers.

    one

    message header

    more

    additional message headers

    returns

    new message

    Definition Classes
    MessageBuilder
  5. def addHeaders(headers: Seq[Header]): HttpResponse

    Creates message with additional headers.

    Creates message with additional headers.

    headers

    message headers

    returns

    new message

    Definition Classes
    MessageBuilder
  6. def as[T](implicit parser: BodyParser[T]): T

    Gets message body as instance of T.

    Gets message body as instance of T.

    parser

    body parser

    Definition Classes
    HttpMessage
  7. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  8. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  9. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  10. def equals(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  11. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  12. def getAttribute[T](name: String): Option[T]

    Gets attribute value with given name.

    Gets attribute value with given name.

    name

    attribute name

    Definition Classes
    HttpMessage
  13. def getAttributeOrElse[T](name: String, default: ⇒ T): T

    Gets attribute value with given name, or returns default if attribute not present.

    Gets attribute value with given name, or returns default if attribute not present.

    name

    attribute name

    default

    default value

    Definition Classes
    HttpMessage
  14. final def getClass(): Class[_]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  15. def getHeader(name: String): Option[Header]

    Gets first header with given name.

    Gets first header with given name.

    Definition Classes
    HttpMessage
  16. def getHeaderOrElse(name: String, default: ⇒ Header): Header

    Gets first header with given name, or returns default if header not present.

    Gets first header with given name, or returns default if header not present.

    Definition Classes
    HttpMessage
  17. def getHeaderValue(name: String): Option[String]

    Gets first header value with given name.

    Gets first header value with given name.

    Definition Classes
    HttpMessage
  18. def getHeaderValueOrElse(name: String, default: ⇒ String): String

    Gets first header value with given name, or returns default if header not present.

    Gets first header value with given name, or returns default if header not present.

    Definition Classes
    HttpMessage
  19. def getHeaderValues(name: String): Seq[String]

    Gets header values with given name.

    Gets header values with given name.

    Definition Classes
    HttpMessage
  20. def getHeaders(name: String): Seq[Header]

    Gets headers with given name.

    Gets headers with given name.

    Definition Classes
    HttpMessage
  21. def hasHeader(name: String): Boolean

    Tests for header with given name.

    Tests for header with given name.

    Definition Classes
    HttpMessage
  22. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  23. def isClientError: Boolean

    Tests for client error status.

  24. def isInformational: Boolean

    Tests for informational status.

  25. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  26. def isRedirection: Boolean

    Tests for redirection status.

  27. def isServerError: Boolean

    Tests for server error status.

  28. def isSuccessful: Boolean

    Tests for successful status.

  29. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  30. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  31. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  32. def putAttributes(one: (String, Any), more: (String, Any)*): HttpResponse

    Creates message with supplied attributes.

    Creates message with supplied attributes.

    one

    attribute

    more

    additional attribute

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    If attribute already exists, its value is replaced.

  33. def putAttributes(attributes: Map[String, Any]): HttpResponse

    Creates message with supplied attribute.

    Creates message with supplied attribute.

    attributes

    attributes

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    If attribute already exists, its value is replaced.

  34. def putHeaders(one: Header, more: Header*): HttpResponse

    Creates message with supplied headers.

    Creates message with supplied headers.

    one

    header

    more

    additional headers

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    All previous headers with same name are removed.

  35. def putHeaders(headers: Seq[Header]): HttpResponse

    Creates message with supplied headers.

    Creates message with supplied headers.

    headers

    message headers

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    All previous headers with same name are removed.

  36. def reasonPhrase: String

    Gets reason phrase.

  37. def removeAttributes(one: String, more: String*): HttpResponse

    Creates message excluding attributes with given names.

    Creates message excluding attributes with given names.

    one

    attribute name

    more

    additional attribute names

    returns

    new message

    Definition Classes
    MessageBuilder
  38. def removeAttributes(names: Seq[String]): HttpResponse

    Creates message excluding attributes with given names.

    Creates message excluding attributes with given names.

    names

    attribute names

    returns

    new message

    Definition Classes
    MessageBuilder
  39. def removeHeaders(one: String, more: String*): HttpResponse

    Creates message excluding headers with given names.

    Creates message excluding headers with given names.

    one

    header name

    more

    additional header names

    returns

    new message

    Definition Classes
    MessageBuilder
  40. def removeHeaders(names: Seq[String]): HttpResponse

    Creates message excluding headers with given names.

    Creates message excluding headers with given names.

    names

    header names

    returns

    new message

    Definition Classes
    MessageBuilder
  41. def setAttributes(one: (String, Any), more: (String, Any)*): HttpResponse

    Creates message with supplied attributes.

    Creates message with supplied attributes.

    one

    message attribute

    more

    additional message attributes

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    All previous attributes are removed.

  42. def setHeaders(one: Header, more: Header*): HttpResponse

    Creates message with supplied headers.

    Creates message with supplied headers.

    one

    message header

    more

    additional message headers

    returns

    new message

    Definition Classes
    MessageBuilder
    Note

    All previous headers are removed.

  43. def setStatus(status: ResponseStatus): HttpResponse

    Creates response with new status.

    Creates response with new status.

    returns

    new response

  44. def setVersion(version: HttpVersion): HttpResponse

    Creates response with new HTTP version.

    Creates response with new HTTP version.

    returns

    new response

  45. def status: ResponseStatus

    Gets response status.

  46. def statusCode: Int

    Gets status code.

  47. final def synchronized[T0](arg0: ⇒ T0): T0
    Definition Classes
    AnyRef
  48. def toString(): String
    Definition Classes
    AnyRef → Any
  49. def version: HttpVersion

    Gets HTTP version.

    Gets HTTP version.

    Definition Classes
    HttpMessage
  50. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  51. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  52. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()

Inherited from MessageBuilder[HttpResponse]

Inherited from HttpMessage

Inherited from AnyRef

Inherited from Any

Ungrouped