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 对象吗 怎么一个乱码 一个正常,,求解决

回答:

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/")

回答:

推荐下 https://github.com/parnurzeal/gorequest

以上是 go request包发送请求后,返回编码出现乱码? 的全部内容, 来源链接: utcz.com/p/183539.html

回到顶部