Could not get the result from an HTTPS JSON Call with Bearer

Hello

I am trying to call a secure service using HTTP POST with JSON format (in and out). I do not get any error but I have not been able to write the result to log or to terminal to see it. Would you please help me? I pasted the code at the bottom.

Regards, Ozcan

NOT : I have successfully called the servis using c#, postman and advanced rest client

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpMethods, HttpRequest}
import akka.http.scaladsl.model.headers.RawHeader
import org.slf4j.LoggerFactory
import scala.util.{Failure, Success}

object Main2 {
val dataAsJson=“SOME JSON DATA”

val log = LoggerFactory.getLogger(“Main”)

val request = HttpRequest(
method = HttpMethods.POST,
uri = “SOME HTTPS SERVICE”,
entity = HttpEntity(
ContentTypes.application/json,
dataAsJson
)
).withHeaders(RawHeader(“Authorization”, “Bearer SOME TOKEN”))

def simpleRequest() = {
implicit val system = ActorSystem(Behaviors.empty, “SingleRequest”)
implicit val executionContext = system.executionContext

log.info("request {}", request)

val responseFuture = Http().singleRequest(request)

responseFuture
  .onComplete {
    case Success(res) => println(res.toString()) //THIS PART IS NOT WORKING
    case Failure(_) => sys.error("something wrong")
  }

/*
for(response <- responseFuture) {
  log.info("response received {}", response)
  log.info("notified about EC Failure")
}
 */

//responseFuture.flatMap(_.entity.toStrict(5 seconds)).map(_.data.utf8String).foreach(println)

}

def main(args: Array[String]): Unit =
{
simpleRequest()
}
}

I guess you need to consume the response entity at the correct position.
In a similar situation sth like this worked for me:

  case class Ctx(title: String, personsFound: List[String] = List.empty, content: String)

  def fetchContent(ctx: Ctx): Future[Ctx] = {
    logger.info(s"About to read `extract` from Wikipedia entry with title: ${ctx.title}")
    val encodedTitle = URLEncoder.encode(ctx.title, "UTF-8")

    val requestURL = s"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=$encodedTitle"
    Http().singleRequest(HttpRequest(uri = requestURL))
      // Consume the streamed response entity
      // Doc: https://doc.akka.io/docs/akka-http/current/client-side/request-level.html
      .flatMap(_.entity.toStrict(2.seconds))
      .map(_.data.utf8String.split("\"extract\":").reverse.head)
      .map(content => ctx.copy(content = content))
  }

Hope that helps
Paul

Hello
Thanks for the answer. Sorry! I am new to scala. I tried using and calling the code you provided as it is as seen below. It runs, but still nothing is printed to the terminal when future is completed. Probably I do not know how to use the Futures. I know that I am making a simple mistake but could not see it myself. I will appreciate your helps:

val personsFound: List[String] = List.empty
val ctx = Ctx("anytitle", personsFound,"")
val responseFuture:Future[Ctx] = fetchContent(ctx)

responseFuture
  .onComplete {
    case Success(res) => logger.info(s"Done with title: ${res.content}")
    case Failure(_) => logger.info(s"Done with title err") //sys.error("something wrong")
  }

OUTPUT:

Sorry, I forgot to mention that you need to provide a valid value for the titles attribute.
In a Browser:

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Adam

this yields a JSON with an extract attribute.

Hello
It is not related what is returned or not. Even this simple code does not print anything. I am just trying to print “IT IS OK” to terminal assigning a value to var result inside the onComplete. But it does not work. I am simply missing something about how Futures work, but what?

var result =""

responseFuture
  .onComplete {
    case Success(res) => result="IT IS OK"
    case Failure(_) => logger.info(s"Done with title err") //sys.error("something wrong")
  }

logger.info(s"A title: ${result}")

This:

yields:

...About to read `extract` from Wikipedia entry with title: Adam
...Title: Adam yields content: "Adam is the name given in Genesis 1-5 to the first human...

Regards
Paul

Hello
Thank you for your responses. I think what happens is when I run it in the İntelliJ terminal or in windows command prompt in does not work. But when I run in the İntelliJ sbt shell, it works.
Many thanks
Kind Regards
Ozcan

NOTE:
Java version is 16.0.2

Build.sbt is

version := “0.1”
scalaVersion := “2.13.8”
val AkkaVersion = “2.6.18”
val AkkaHttpVersion = “10.2.7”

libraryDependencies ++= Seq(
“com.typesafe.akka” %% “akka-actor-typed” % AkkaVersion,
“com.typesafe.akka” %% “akka-stream” % AkkaVersion,
“com.typesafe.akka” %% “akka-http” % AkkaHttpVersion,
“com.typesafe.akka” %% “akka-slf4j” % AkkaVersion,
“ch.qos.logback” % “logback-classic” % “1.2.10” % Runtime
)