【问题标题】:http4s decompress gzipped http responsehttp4s 解压 gzipped http 响应
【发布时间】:2020-11-13 05:30:18
【问题描述】:

我尝试在客户端解压缩 gzip 后的简单响应。 使用 http4s 的合适方法是什么?

import cats.effect.{Blocker, ContextShift, IO, Timer}
import java.util.concurrent._
import org.http4s.{Header, Headers, HttpVersion, Method, Request}
import org.http4s.client.{Client, JavaNetClientBuilder}
import org.http4s.implicits._

import scala.concurrent.ExecutionContext.global
implicit val cs: ContextShift[IO] = IO.contextShift(global)
implicit val timer: Timer[IO] = IO.timer(global)

val blockingPool = Executors.newFixedThreadPool(5)
val blocker = Blocker.liftExecutorService(blockingPool)
val httpClient: Client[IO] = JavaNetClientBuilder[IO](blocker).create
val uriYandex = uri"https://ya.ru"

val lstHeader: List[Header] =List(
  Header("Accept","text/plain")
  ,Header("Accept-Charset","utf-8")
  ,Header("Accept-Encoding","*")
)

val request2 = Request[IO](Method.GET, uriYandex, HttpVersion.`HTTP/2.0`, Headers(lstHeader))
val httpReq = httpClient.expect[String](request2)
val app = httpReq.map(resString => resString)

app.unsafeRunSync

http4s 版本“0.21.3” 如果我在 IDEA Scala Worksheet 中运行它。它工作正常并输出:

res0: String =

res0: 字符串 = “ ??????????|?r?H??P?320???,Y??+d[v{??????” ?????%??9?'&6&66f???????3 ?{????7?/?

我尝试了不同的解码器,但出现以下错误:

失败(java.util.zip.ZipException:不是 GZIP 格式)

【问题讨论】:

  • FWIW,“接受编码:*”没有任何意义。你想达到什么目的?
  • 在这两种情况下我都看不到响应标头,但看起来像“Accept-Encoding: *”服务器不压缩响应和使用 gzip,响应被压缩。
  • 如果您不想压缩,正确的发送方式是“Accept-Encoding: identity”。请参阅 greenbytes.de/tech/webdav/rfc7231.html#header.accept-encoding>。

标签: scala http gzip http4s


【解决方案1】:

你不能只发送Accept-Encoding header,因为当你发送httpClient.expect[String]时,HTTP客户端会尝试将数据解码为字符串,它并不知道它需要先解压数据.

尝试使用GZip middleware

【讨论】:

  • 是的,我觉得使用Client GZip中间件是一种解决方案。但是没有使用它的例子。
【解决方案2】:

谢谢大家。我在下次使用 GZip 时解决了我的问题。

import org.http4s.client.middleware.GZip
val gzClient = GZip()(httpClient)
val httpReq = gzClient.expect[String](request2)
val app = httpReq.map(resString => resString)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    相关资源
    最近更新 更多