gpt4 book ai didi

Scala:http4s 对于在curl/requests 中工作的相同请求给出 401 Unauthorized

转载 作者:行者123 更新时间:2023-12-02 00:11:22 27 4
gpt4 key购买 nike

我使用http4s v0.19.0尝试了以下代码:

import cats.effect._

def usingHttp4s(uri: String, bearerToken: String)(implicit cs: ContextShift[IO]): String = {
import scala.concurrent.ExecutionContext
import org.http4s.client.dsl.io._
import org.http4s.headers._
import org.http4s.Method._
import org.http4s._
import org.http4s.client._


import org.http4s.client.middleware._

val blockingEC = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(5))

val middlewares = Seq(
RequestLogger[IO](logHeaders = true, logBody = true, redactHeadersWhen = _ => false)(_),
FollowRedirect[IO](maxRedirects = 5)(_)
)

val client = middlewares.foldRight(JavaNetClientBuilder(blockingEC).create[IO])(_.apply(_))

val req = GET(
Uri.unsafeFromString(uri),
Authorization(Credentials.Token(AuthScheme.Bearer, bearerToken))
)
client.expect[String](req).unsafeRunSync()
}

我收到以下错误:

[error] (run-main-0) org.http4s.client.UnexpectedStatus: unexpected HTTP status: 401 Unauthorized
[error] org.http4s.client.UnexpectedStatus: unexpected HTTP status: 401 Unauthorized

不仅如此,我的程序从未退出(我是否必须关闭某些客户端!?),即使我连接了日志中间件,它也从未打印请求

我接下来尝试了@li-haoyi的request库,这没有返回错误:

def usingLiHaoyiRequest(uri: String, bearerToken: String): String =
requests.get(uri, headers = Iterable("Authorization" -> s"Bearer $bearerToken")).text()

上面的代码适用于相同的uri和相同的baseToken,所以我的 token 不可能是错误的。为了更加确定,我尝试了curl:

curl -L -H "Authorization: Bearer ${BEARER}" ${URI}

此问题也会发生在 http4s v0.18.19 中(即使使用显式 Json 和接受 header ):

import io.circle.Json

def usingHttp4s(uri: String, bearerToken: String): Json = {
import org.http4s.client.dsl.io._
import org.http4s.headers._
import org.http4s.Method._
import org.http4s._
import org.http4s.client.blaze.Http1Client
import org.http4s.client.middleware._
import org.http4s.circe._
import org.http4s.MediaType._

val program = for {
c <- Http1Client[IO]()
client = FollowRedirect(maxRedirects = 5)(c)
req = GET(
Uri.unsafeFromString(uri),
Authorization(Credentials.Token(AuthScheme.Bearer, bearerToken)),
Accept(`application/json`)
)
res <- client.expect[Json](req)
} yield res

program.unsafeRunSync()
}

所以我的问题是:

  1. 为什么 requestscurl 都能工作,但 http4s 却给了我401 相同的请求?
  2. 为什么我的 http4s 版本永远不会退出?
  3. 为什么请求记录器中间件不记录请求?

最佳答案

gitter room 中所述,该错误存在于 http4s 中,它不会将授权 header 转发到重定向,但curl 和 requests 都会转发(只要转发到同一子域)。

关于Scala:http4s 对于在curl/requests 中工作的相同请求给出 401 Unauthorized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53783653/

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