douzhuanfen5923 2018-06-03 17:45
浏览 2977
已采纳

在Go中执行HTTP请求时出现乱码

I met a Garbled string question when do Get request in Go, the code is:

req , err:= http.NewRequest(httpMethod, url,strings.NewReader(""))
req.Header.Add("Accept","application/json")
resp, err := http.DefaultClient.Do(req)
body,err := ioutil.ReadAll(resp.Body)
ret := string(body)
log.Warningf("ret: %+v", ret)

if the ret contains only english, it's correct, if contains Chinese, it has garbled string, how to solve this problem, thanks all!

  • 写回答

2条回答 默认 最新

  • ds753947 2018-06-03 20:58
    关注

    Go strings can hold any type of characters, but when printing them the chars are interpreted as utf-8.

    You can try adding:

    req.Header.Add("Accept-Charset","utf-8")
    

    If that does not work, you can try using this package to convert from whatever charset it is to utf-8:

    https://godoc.org/golang.org/x/text/encoding

    The charset depends on the page you are requesting. If it is html, the charset is sometimes specified like this in the response headers:

    Content-Type: text/html; charset=utf-8
    

    So you need to figure out what the charset is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部