akka http 客户端遵循重定向

Dav*_*lla 3 akka akka-http

akka-http 文档提供了一个查询 http 服务的示例:

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

我如何告诉 akka-http 自动遵循重定向,而不是接收代码 == 302 的 HttpResponse?

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()
  }

}
Run Code Online (Sandbox Code Playgroud)

mat*_*its 6

你不能告诉 Akka-http 客户端自动执行此操作。这是 Akka 项目的一个开放问题:https ://github.com/akka/akka-http/issues/195

您可以使用以下方法手动处理此问题:

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

您可能希望维护重定向的次数以避免无限循环。