Skip to content

Instantly share code, notes, and snippets.

@fran0x
Created September 8, 2016 17:53
Show Gist options
  • Save fran0x/924e7a74f2d0f528f3781ae1aa357f04 to your computer and use it in GitHub Desktop.
Save fran0x/924e7a74f2d0f528f3781ae1aa357f04 to your computer and use it in GitHub Desktop.
Simple snippet to retrieve a web in an asynchronous manner
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{StatusCodes, _}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}
object Http extends App {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
request("http://akka.io") onComplete {
println(_)
}
def request(uri: String): Future[Try[String]] = {
Http().singleRequest(HttpRequest(uri = uri)) flatMap {
response =>
response.status match {
case StatusCodes.OK => Unmarshal(response.entity).to[String].map(Success(_))
case _ => Unmarshal(response.entity).to[String].map(x => Failure(new Exception(x)))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment