如何在发送HTTP请求时控制gzip压缩?

huangapple go评论84阅读模式
英文:

(Go) How to control gzip compression when sending http request?

问题

我想问问你们所有人,在发送HTTP POST消息时如何控制gzip压缩。我总是在发送的HTTP请求中添加了"Accept-Encoding: gzip"作为HTTP请求头。但是我不想使用gzip压缩。我该如何处理?

在执行http.NewRequest之前,我一直使用transport类型的DisableCompression。我已经尝试将DisableCompression的值设置为true和false,但是到目前为止都无法正常工作。

我的代码示例如下:

//gzip
tr := &http.Transport{
    DisableCompression: true,
}
//client := &http.Client{}
client := &http.Client{Transport: tr}

req, err := http.NewRequest(
    "POST",
    reqUrl,
    bytes.NewBuffer(bytesMessage),
)

//设置HTTP头
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
req.Header.Add("Accept", "*/*")
req.Header.Del("Accept-Encoding")

//发送HTTP请求
resp, err := client.Do(req)

我使用的Go版本是1.5。

提前感谢。

英文:

I'd like to ask all of you how to control gzip compression when requesting HTTP Post messages.
"Accept-Encoding: gzip" as Http request headers was always added to http request I sent.
But I don't want to use gzip compression.
How can I manage that?

I've always used DisableCompression of transport type before executing http.NewRequest.
And I already tried to set both of value true and false to DisableCompression.
However it can't work well so far.

My part of code sample is as below.

//gzip
tr := &http.Transport{
	DisableCompression: true,
}
//client := &http.Client{}
client := &http.Client{Transport: tr}

req, err := http.NewRequest(
	"POST",
	reqUrl,
	bytes.NewBuffer(bytesMessage),
)

//Set Http Headers
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
req.Header.Add("Accept", "*/*")
req.Header.Del("Accept-Encoding")

//HTTP request
resp, err := client.Do(req)

Go version I'm using is 1.5.

Thanks in advance.

答案1

得分: 12

尝试使用以下代码:

req.Header.Set("Accept-Encoding", "identity")
英文:

Try

req.Header.Set("Accept-Encoding", "identity")

huangapple
  • 本文由 发表于 2015年11月2日 10:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/33469723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定