5

我尝试使用以下代码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 的请求库,没有返回错误:

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和接受标头):

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. 为什么两者都requests工作curlhttp4s给我 401 相同的请求?
  2. 为什么我的http4s版本永远不会退出?
  3. 为什么请求记录器中间件不记录请求?
4

1 回答 1

5

gitter room中所述,该错误在于http4s不会将授权标头转发到重定向,但 curl 和请求都可以(只要转发到相同的子域)。

于 2018-12-17T15:46:43.747 回答