httpoison - 响应正文显示乱码文本而不是HTML

tld*_*ldr 2 utf-8 elixir httpoison

如果我尝试:

url = "https://www.economist.com/news/finance-and-economics/21727073-economists-struggle-work-out-how-much-free-economy-comes-cost"    
{:ok, %HTTPoison.Response{status_code: 200, body: body}} = HTTPoison.get(url)
IO.binwrite body
Run Code Online (Sandbox Code Playgroud)

我在控制台中看到乱码文本(而不是html).但如果我在网页上查看源代码,我会在那里看到HTML.我究竟做错了什么?

PS:它与js http客户端(axios.js)工作正常,不知道为什么它不适用于httpoison

Dog*_*ert 5

该URL以gzip形式返回正文,并通过发送标头来指示Content-Encoding: gzip.hackney,HTTPoison库建立在,不会自动解码.此功能可能会在某些时候添加.在此之前,您可以使用:zlib模块自行解码身体,如果Content-Encodinggzip:

url = "https://www.economist.com/news/finance-and-economics/21727073-economists-struggle-work-out-how-much-free-economy-comes-cost"

{:ok, %HTTPoison.Response{status_code: 200, headers: headers, body: body}} = HTTPoison.get(url)

gzip? = Enum.any?(headers, fn {name, value} ->
  # Headers are case-insensitive so we compare their lower case form.
  :hackney_bstr.to_lower(name) == "content-encoding" &&
    :hackney_bstr.to_lower(value) == "gzip"
end)

body = if gzip?, do: :zlib.gunzip(body), else: body

IO.write body
Run Code Online (Sandbox Code Playgroud)