Last active
June 25, 2023 15:33
-
-
Save dacr/50b74b837008af547fd44e00f9d47944 to your computer and use it in GitHub Desktop.
Fully asynchronous http client call with json response using akka-http will work in all cases, even with chunked responses ! / published by https://github.com/dacr/code-examples-manager #bcde601a-cafa-4f5a-9852-75386e33089a/fc3bd62b52c70bbced235722606fe8214f1f4756
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
// summary : Fully asynchronous http client call with json response using akka-http will work in all cases, even with chunked responses ! | |
// keywords : scala, actors, akka, http-client, client, json, json4s, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : bcde601a-cafa-4f5a-9852-75386e33089a | |
// created-on : 2018-06-19T19:10:04Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "2.13.8" | |
//> using dep "com.typesafe.akka::akka-http:10.2.7" | |
//> using dep "com.typesafe.akka::akka-stream:2.6.18" | |
//> using dep "de.heikoseeberger::akka-http-json4s:1.38.2" | |
//> using dep "org.json4s::json4s-jackson:4.0.3" | |
//> using dep "org.slf4j:slf4j-nop:1.7.32" | |
// --------------------- | |
import akka.http.scaladsl._ | |
import akka.http.scaladsl.model._ | |
import akka.http.scaladsl.unmarshalling.Unmarshal | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
import scala.util.{Success, Failure} | |
import de.heikoseeberger.akkahttpjson4s.Json4sSupport._ | |
import org.json4s.{DefaultFormats, JValue} | |
import org.json4s.jackson.JsonMethods._ | |
import org.json4s._ | |
object TestThat { | |
implicit val system = akka.actor.ActorSystem("MySystem") | |
implicit val executionContext = system.dispatcher | |
implicit val serialization = jackson.Serialization | |
implicit val formats = DefaultFormats | |
// curl -s -H "accept: application/json" http://httpbin.org/json | jq | |
val uri = s"http://httpbin.org/json" | |
val futureResponse = Http().singleRequest(HttpRequest(uri = uri)) | |
val futureResult = futureResponse.transformWith { | |
case Success(response) => Unmarshal(response.entity).to[JValue] | |
case Failure(ex) => | |
ex.printStackTrace() | |
throw ex | |
} | |
futureResult.map { result => | |
println(pretty(render(result))) | |
System.out.flush() | |
system.terminate() | |
} | |
// Do not exit before the future has completed ;) | |
def andWait(): Unit = Await.ready(futureResult, 10.seconds) | |
} | |
TestThat.andWait() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment