gpt4 book ai didi

akka http 客户端跟随重定向

转载 作者:行者123 更新时间:2023-12-02 00:43:18 25 4
gpt4 key购买 nike

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

}

最佳答案

您不能告诉 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

您可能希望对重定向的次数进行计数,以避免无限循环。

关于akka http 客户端跟随重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45379699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com