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

在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 el-table输入多维数组怎么实现
  • ¥15 安装GroudingDINO RuntimeError: Error compiling objects for extension
  • ¥15 关于推送项目到github的问题
  • ¥15 急!C++指针编写相关的问题
  • ¥15 kerberos身份认证配置问题
  • ¥30 用python写一个多签情况下波场的代理资源和回收资源
  • ¥15 怎么在matlab中输出显示泵的流量-扬程和管路损失与流量均在一个表格里
  • ¥15 matlab学期例题代码答疑
  • ¥15 在线手电筒追加按钮JS