David Portabella
David Portabella

Reputation: 12720

akka http client follow redirect

The akka-http documentation provides an example to query a http service:

http://doc.akka.io/docs/akka-http/current/scala/http/client-side/request-level.html

how can I tell akka-http to automatically follow redirects, instead of receiving a HttpResponse with code == 302?

akka 2.5.3, akka-http 10.0.9

import akka.actor.{ Actor, ActorLogging }
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.{ ActorMaterializer, ActorMaterializerSettings }
import akka.util.ByteString

class Myself extends Actor
  with ActorLogging {

  import akka.pattern.pipe
  import context.dispatcher

  final implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system))

  val http = Http(context.system)

  override def preStart() = {
    http.singleRequest(HttpRequest(uri = "http://akka.io"))
      .pipeTo(self)
  }

  def receive = {
    case HttpResponse(StatusCodes.OK, headers, entity, _) =>
      entity.dataBytes.runFold(ByteString(""))(_ ++ _).foreach { body =>
        log.info("Got response, body: " + body.utf8String)
      }
    case resp @ HttpResponse(code, _, _, _) =>
      log.info("Request failed, response code: " + code)
      resp.discardEntityBytes()
  }

}

Upvotes: 3

Views: 3386

Answers (1)

mattinbits
mattinbits

Reputation: 10428

You can't tell Akka-http client to do this automatically. It is an open issue for the Akka project: https://github.com/akka/akka-http/issues/195

You could handle this manually with something like:

case resp @ HttpResponse(StatusCodes.Redirection(_, _, _, _), headers, _, _) =>
  //Extract Location from headers and retry request with another pipeTo

You probably would want to maintain a count of the number of times you get redirected to avoid an infinite loop.

Upvotes: 6

Related Questions