登录
首页 >  Golang >  Go问答

使用http.NewRequest调用rest API时,响应正文乱码

来源:stackoverflow

时间:2024-04-21 23:42:39 234浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用http.NewRequest调用rest API时,响应正文乱码》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我尝试使用 go 调用 api。使用 postman 时一切正常。但如果我使用 postman 的 go 代码,响应就会出现乱码/不清楚。

在我正在使用的代码下方:

func callapi() {
    url := "https://url"

    req, _ := http.newrequest("get", url, nil)

    req.header.add("authorization", "bearer token is normaly here")
    req.header.add("user-agent", "postmanruntime/7.19.0")
    req.header.add("accept", "accept: application/json")
    req.header.add("cache-control", "no-cache")
    req.header.add("postman-token", "postman token normaly here")
    req.header.add("host", "host normaly here")
    req.header.add("accept-encoding", "gzip, deflate")
    req.header.add("connection", "keep-alive")
    req.header.add("cache-control", "no-cache")

    res, _ := http.defaultclient.do(req)

    defer res.body.close()
    body, _ := ioutil.readall(res.body)


    fmt.println(string(body))
}

当我使用 fmt.println(string(body)) 时得到的响应如下所示。我还使用此代码尝试了其他 api,并得到了相同的结果。

r�痱�

我还尝试将 json 解组为结构,但出现以下错误 寻找值开头的无效字符“\x1f”

我认为这与解码有关。但我不知道是什么。


解决方案


您要求服务器发送压缩的内容(req.header.add("accept-encoding", "gzip, deflate")),这就是您得到的:gzip 响应,由响应标头指示: 内容编码:[gzip]

删除该标头(不要设置 accept-encoding 请求标头),您应该获得纯 json 响应。或者自己解码 gzip 响应。

请注意,如果省略此标头,默认传输仍会请求 gzip 编码,但也会透明地对其进行解码。由于您明确请求它,因此不会发生透明的自动解码。这记录在 Transport.DisableCompression 字段中:

// DisableCompression, if true, prevents the Transport from
// requesting compression with an "Accept-Encoding: gzip"
// request header when the Request contains no existing
// Accept-Encoding value. If the Transport requests gzip on
// its own and gets a gzipped response, it's transparently
// decoded in the Response.Body. However, if the user
// explicitly requested gzip it is not automatically
// uncompressed.
DisableCompression bool

好了,本文到此结束,带大家了解了《使用http.NewRequest调用rest API时,响应正文乱码》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>