【问题标题】:httpoison - response body showing garbled text instead of htmlhttpoison - 显示乱码文本而不是 html 的响应正文
【发布时间】:2018-02-05 01:53:36
【问题描述】:

如果我尝试:

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

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

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

【问题讨论】:

    标签: utf-8 elixir httpoison


    【解决方案1】:

    该 URL 以 gzip 格式返回正文,并通过发送标头 Content-Encoding: gzip 来表明这一点。 hackney,建立在 HTTPoison 库之上,不会自动解码。此功能will likely be added at some point。在那之前,如果Content-Encodinggzip,您可以使用:zlib 模块自己解码主体:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多