我尝试使用以下代码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()
}
所以我的问题是:
- 为什么两者都
requests
工作curl
但http4s
给我 401 相同的请求? - 为什么我的
http4s
版本永远不会退出? - 为什么请求记录器中间件不记录请求?