Scala:http4s 为在 curl/requests 中有效的相同请求提供 401 Unauthorized

Scala: http4s giving 401 Unauthorized for same request that works in curl/requests

我使用 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 所以不可能是我的令牌有误。可以肯定的是,我尝试了 curl:

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

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

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 和请求都可以(只要转发是相同的) sub-domain).