go request包发送请求后,返回编码出现乱码?

// test
package main

import (
    "io/ioutil"
    "net/http"
    "os"

    "github.com/mozillazg/request"
)

func main() {
    c := &http.Client{}
    req := request.NewRequest(c)
    resp, _ := req.Get("http://segmentfault.com/")
    defer resp.Body.Close() // **Don't forget close the response body**
    body, _ := ioutil.ReadAll(resp.Body)
    fr, _ := os.Create("request.html")
    fr.Write(body)
    res, _ := http.Get("http://segmentfault.com/")
    truebody, _ := ioutil.ReadAll(res.Body)
    res.Body.Close()
    ft, _ := os.Create("get.html")
    ft.Write(truebody)

}

request包请求结果
request包请求结果

http.get请求输出结果
http.get请求输出结果

出现乱码 而这返回的不都是response 对象吗 怎么一个乱码 一个正常,,求解决

阅读 16k
2 个回答

github.com/mozillazg/request 这个库默认在 request 的Header 中加入了

Content-Encoding:[gzip]

所以返回的body不是text/html,而是一个压缩过的二进制。所以request.html 中是乱码。
代码中加入这么一段:

c := &http.Client{}
req := request.NewRequest(c)
// 追加的代码 开始=====================
req.Headers = map[string]string{
        "Accept-Encoding": "",
}
// 追加的代码 结束=====================
resp, _ := req.Get("http://segmentfault.com/")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题