亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用http.NewRequest調用rest API時,響應正文亂碼

使用http.NewRequest調用rest API時,響應正文亂碼

Go
慕容森 2023-07-31 16:24:14
我嘗試使用 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 解組為結構,但出現以下錯誤 Invalid character '\x1f' looking for beginning of value我認為這與解碼有關。但我不知道是什么。
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

您要求服務器發送壓縮的內容 (?req.Header.Add("Accept-Encoding", "gzip, deflate")),這就是您得到的:gzip 響應,由響應標頭指示:Content-Encoding:[gzip]。

刪除該標頭(不設置Accept-Encoding請求標頭),您應該得到純 JSON 響應?;蛘咦约航獯a 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


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 218 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號