【问题标题】:Does getting Response from Request get all of the body? (golang, net/http)从请求中获取响应是否会获取所有正文? (golang, 网络/http)
【发布时间】:2016-07-05 05:48:36
【问题描述】:

我试图避免浪费流量,仅当我看到正确的 content-typecontent-length 小于设置的阈值时才读取 http 响应正文。

httpRequest, err := http.NewRequest("GET", url, nil)
httpResponse, err := httpClient.Do(httpRequest)
contentType := httpResponse.Header.Get("Content-Type")

// ... check for correct contentType    

// Read body into memory?
content, err := ioutil.ReadAll(httpResponse.Body)

是否正确假设如果我发出 GET 请求,无论我是否调用最后一行 iotuil.ReadAll(httpResponse.Body),我都会获得所有正文?

如果是这样,我能想到的避免浪费流量的唯一方法是使用 HEAD 请求,但如果我真的想读取正文,我将不得不发出另一个 GET 请求。如果我提出 HEAD 请求,我是否也能得到正确的 content-length 值?

最好的策略是什么?

【问题讨论】:

    标签: http go web-crawler


    【解决方案1】:

    如果应用程序不想读取响应正文,应用程序应该关闭它。在最近的 Go 版本中,net/http client will close the underlying network connection instead of slurping up the remainder of the response body from the network.

    可能未设置 Content-Length 标头。在这种情况下,应用程序应该读取到阈值字节数或 EOF。

    在所有情况下,在应用程序完成响应后关闭响应正文。

    不保证对 HEAD 请求的响应包含 Content-Length 标头。

    【讨论】:

    • 感谢您的快速回答。您是说在调用 ioutil.ReadAll(httpResponse.Body) 之前,net/http 不会发送 TCP 数据包 来读取正文?
    • 如果客户端没有读取响应体,则服务器发送数据,直到 TCP 窗口填满或客户端关闭连接。关闭响应正文是减少通过网络传输的数据量的唯一选择。
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2014-06-14
    相关资源
    最近更新 更多