akka http客户端按照重定向

时间:2017-07-28 17:59:32

标签: 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()
  }

}

1 个答案:

答案 0 :(得分:3)

您无法告诉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

您可能希望保留重定向次数以避免无限循环。

相关问题