douzhuanfen5923 2018-06-04 01:45
浏览 2962
已采纳

在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-04 04: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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器