Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/7906717f02d138756353c1758098bd0f to your computer and use it in GitHub Desktop.
Save dacr/7906717f02d138756353c1758098bd0f to your computer and use it in GitHub Desktop.
Simplest sttp http client library json example using akkahttp backend. / published by https://github.com/dacr/code-examples-manager #2b623f40-e7df-4fb8-8b29-05d7907d63a0/457dd18197113ec2fd7daf4b4a5cfd2ea90fcff3
// summary : Simplest sttp http client library json example using akkahttp backend.
// keywords : scala, sttp, http-client, json4s, json, akkahttp
// 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 : 2b623f40-e7df-4fb8-8b29-05d7907d63a0
// created-on : 2020-07-02T10:02:26Z
// managed-by : https://github.com/dacr/code-examples-manager
// execution : scala ammonite script (http://ammonite.io/) - run as follow 'amm scriptname.sc'
import $ivy.`com.softwaremill.sttp.client3::core:3.3.5`
import $ivy.`com.softwaremill.sttp.client3::akka-http-backend:3.3.5`
import $ivy.`com.softwaremill.sttp.client3::json4s:3.3.5`
import $ivy.`com.typesafe.akka::akka-stream:2.6.14`
import $ivy.`org.json4s::json4s-jackson:3.6.11`
import sttp.client3._
import sttp.client3.json4s._
import org.json4s._
import sttp.client3.akkahttp._
import scala.util.{Success, Failure, Try, Left, Right, Either}
import scala.concurrent.{Future, Await}
import scala.concurrent.duration._
object Status { // Embedded within an object to avoid issues between future and ammonite
import scala.concurrent.ExecutionContext.Implicits.global
val backend = AkkaHttpBackend()
implicit val serialization = org.json4s.jackson.Serialization
implicit val formats = org.json4s.DefaultFormats
def check():Unit = {
val jsonFuture = {
basicRequest
.get(uri"http://httpbin.org/ip")
.response(asJson[JValue])
.send(backend)
}
val resultFuture = {
jsonFuture
.map(_.body)
.collect { case Right(json) => json }
.map(json => (json \ "origin").extract[String])
}
Await.result(resultFuture.map(println), 2.seconds) // To avoid exiting before the result is ready to be printed
}
}
Status.check()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment