Created
September 8, 2016 17:53
-
-
Save fran0x/924e7a74f2d0f528f3781ae1aa357f04 to your computer and use it in GitHub Desktop.
Simple snippet to retrieve a web in an asynchronous manner
This file contains hidden or 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
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