简体   繁体   English

http4s 解压 gzipped http 响应

[英]http4s decompress gzipped http response

I try decompress gzipped simple response on client side.我尝试在客户端解压缩 gzipped 的简单响应。 What the appropriate way to do it with http4s?使用 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 version "0.21.3" If I run it in IDEA Scala Worksheet. http4s 版本“0.21.3”如果我在 IDEA Scala 工作表中运行它。 it works fine and output:它工作正常,output:

res0: String = <html class="i-ua_js_no i-ua_css_standart i-ua_browser_ i-ua_browser-engine_ i res0: String = <html class="i-ua_js_no i-ua_css_standart i-ua_browser_ i-ua_browser-engine_i

But if I change,Header("Accept-Encoding","*") into,Header("Accept-Encoding","gzip") server return me gzipped content and output:但是,如果我将 Header("Accept-Encoding","*") 更改为,Header("Accept-Encoding","gzip") 服务器返回我压缩后的内容和 output:

res0: String = "??????????|?r?H??P?320???,Y??+d[v{??????"?????%??9?'&6&66f???????3?{????7?/? res0: String = "??????????|?r?H??P?320???,Y??+d[v{??????"?????% ??9?'&6&66f???????3?{????7?/?

I have tried different decoders, but with this errors:我尝试了不同的解码器,但出现了以下错误:

Failure(java.util.zip.ZipException: Not in GZIP format)失败(java.util.zip.ZipException:不是 GZIP 格式)

You can't just send the Accept-Encoding header, because when you do httpClient.expect[String] , the HTTP client will try to decode the data as a string, and it doesn't know that it needs to decompress the data first.你不能只发送Accept-Encoding header,因为当你做httpClient.expect[String]时,HTTP 客户端会尝试将数据解码为字符串,它不知道它需要先解压缩数据.

Try using theGZip middleware .尝试使用GZip 中间件

Thanks everybody.谢谢大家。 I solve my problem with next using of GZip.我在下次使用 GZip 时解决了我的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM