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

在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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵