http - 如何在Go中请求具有特定字符集的页面?

标签 http go

我正在将软件从Python重写为Go。我在获取http.Get编码的页面时遇到iso-8859-1问题。 Python版本正在运行,但Go版本中没有。

这是可行的:Python

r = requests.get("https://www.bger.ch/ext/eurospider/live/de/php/aza/http/index.php?lang=de&type=show_document&print=yes&highlight_docid=aza://27-01-2016-5A_718-2015")
r.encoding = 'iso-8859-1'
file = open('tmp_python.txt', 'w')
file.write(r.text.strip())
file.close()

这不起作用:转到
package main

import (
    "golang.org/x/net/html/charset"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    link := "https://www.bger.ch/ext/eurospider/live/de/php/aza/http/index.php?lang=de&type=show_document&print=yes&highlight_docid=aza://27-01-2016-5A_718-2015"
    resp, err := http.Get(link)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    reader, err := charset.NewReader(resp.Body, "iso-8859-1")
    if err != nil {
        panic(err)
    }

    content, err := ioutil.ReadAll(reader)
    if err != nil {
        panic(err)
    }
    log.Println(string(content))
}

我的浏览器和Python给出了相同的结果,但Go版本却没有。我该如何解决?

编辑

我认为Go可以重定向。使用Python不会发生这种情况。

编辑2

我的问题写得不好。我有两个问题:1)编码2)返回错误的页面。不知道有没有关系。

我将为第二个问题打开一个新线程。

最佳答案

NewReader的第二个参数记录为contentType而不是字符编码。这意味着它期望使用HTTP header 中的Content-Type字段的值。因此,正确的用法是:

reader, err := charset.NewReader(resp.Body, "text/html; charset=iso-8859-1")

这完美地工作。

请注意,如果给定的contentType内部没有有用的字符集定义,它将查看主体本身以确定字符集。并且尽管此页的HTTP header 有一个清晰的
Content-Type: text/html;charset=iso-8859-1

返回的实际HTML文档定义了不同的字符集编码:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

如果您的代码中contentType设置错误,它将采用HTML中错误声明的字符集编码。

关于http - 如何在Go中请求具有特定字符集的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106092/

相关文章:

php - 按钮停止发出 POST 请求

http - 在 Gradle 中传递代理信息是怎么回事?

去 channel 不工作

python - HTML到文本,例如Python的BeautifulSoup

go - 如何在 Go 中获取命令参数?

node.js - Node js HTTP 服务器/静态 Servlet POST 请求

javascript - 从 CDN 提供许多依赖项会减慢站点速度吗?

loops - 是什么导致空的 Go for 循环锁定程序?

go - 我的神经网络(从头开始)训练,让它离目标更远

http - gzip 压缩对移动设备有用吗?