Last active
August 29, 2015 13:57
-
-
Save anderssonfilip/9528419 to your computer and use it in GitHub Desktop.
Spray Client example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Akka Actor system | |
import akka.actor.ActorSystem | |
// HTTP related imports | |
import spray.http.{ HttpRequest, HttpResponse } | |
import spray.client.pipelining.{ Get, sendReceive } | |
// Futures related imports | |
import scala.concurrent.Future | |
import scala.util.{ Success, Failure } | |
// http://stackoverflow.com/questions/20593280/error-with-akka | |
// add dependency typesafe-config.jar | |
// Need to wrap in a package to get application supervisor actor | |
// "you need to provide exactly one argument: the class of the application supervisor actor" | |
package main.scala { | |
// trait with single function to make a GET request | |
trait WebClient { | |
def get(url: String): Future[String] | |
} | |
// implementation of WebClient trait | |
class SprayWebClient(implicit system: ActorSystem) extends WebClient { | |
import system.dispatcher | |
// create a function from HttpRequest to a Future of HttpResponse | |
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive | |
// create a function to send a GET request and receive a string response | |
def get(url: String): Future[String] = { | |
val futureResponse = pipeline(Get(url)) | |
futureResponse.map(_.entity.asString) | |
} | |
} | |
object Program extends Application { | |
import system.dispatcher // execution context for futures | |
// bring the actor system in scope | |
implicit val system = ActorSystem() | |
// create the client | |
val webClient = new SprayWebClient()(system) | |
// send GET request with absolute URI | |
val futureResponse = webClient.get("https://ripple-rest.herokuapp.com/api/v1/status") | |
// wait for Future to complete | |
futureResponse onComplete { | |
case Success(response) => println(response) | |
case Failure(error) => println("An error has occured: " + error.getMessage) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment