Created
February 24, 2016 00:45
-
-
Save ASRagab/03f6a37a2b2981bd4cf3 to your computer and use it in GitHub Desktop.
Simple Connection Level Akka Http 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
package httpclient | |
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport | |
import akka.http.scaladsl.model.StatusCodes._ | |
import akka.http.scaladsl.model.{HttpRequest, HttpResponse} | |
import akka.http.scaladsl.unmarshalling.Unmarshal | |
import akka.stream.ActorMaterializer | |
import akka.stream.scaladsl._ | |
import spray.json._ | |
import scala.concurrent.{Await, Future} | |
import scala.concurrent.duration._ | |
/** | |
* Created by ASRagab on 2/23/16. | |
*/ | |
object JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol { | |
case class IpInfo(ip: String) | |
implicit val format = jsonFormat1(IpInfo.apply) | |
} | |
object ConnectionLevel extends App { | |
implicit val system = ActorSystem() | |
implicit val ec = system.dispatcher | |
implicit val materializer = ActorMaterializer() | |
val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("api.ipify.org") | |
val responseFuture = | |
Source.single(HttpRequest(uri = "/?format=json")) | |
.via(connectionFlow) | |
.runWith(Sink.headOption) | |
import JsonProtocol._ | |
responseFuture map { res => | |
res.get.status match { | |
case OK => | |
Unmarshal(res.get.entity).to[IpInfo].map { info => | |
println(s"The Information for my ip is $info") | |
shutdown | |
} | |
case _ => Unmarshal(res.get.entity).to[String].map { cause => | |
println(s"Response status ${res.get.entity} received because $cause") | |
shutdown | |
} | |
} | |
} | |
def shutdown() = { | |
system.terminate | |
Await.result(system.whenTerminated, 5 seconds) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment