Go语言net/http客户端

使用go doc帮助获取到的net/http帮助如下
type Client struct {
// Transport specifies the mechanism by which individual
// HTTP requests are made.
// If nil, DefaultTransport is used.
Transport RoundTripper

  1. // CheckRedirect specifies the policy for handling redirects.<br /> // If CheckRedirect is not nil, the client calls it before<br /> // following an HTTP redirect. The arguments req and via are<br /> // the upcoming request and the requests made already, oldest<br /> // first. If CheckRedirect returns an error, the Client's Get<br /> // method returns both the previous Response (with its Body<br /> // closed) and CheckRedirect's error (wrapped in a url.Error)<br /> // instead of issuing the Request req.<br /> // As a special case, if CheckRedirect returns ErrUseLastResponse,<br /> // then the most recent response is returned with its body<br /> // unclosed, along with a nil error.<br /> //<br /> // If CheckRedirect is nil, the Client uses its default policy,<br /> // which is to stop after 10 consecutive requests.<br /> CheckRedirect func(req *Request, via []*Request) error
  2. // Jar specifies the cookie jar.<br /> //<br /> // The Jar is used to insert relevant cookies into every<br /> // outbound Request and is updated with the cookie values<br /> // of every inbound Response. The Jar is consulted for every<br /> // redirect that the Client follows.<br /> //<br /> // If Jar is nil, cookies are only sent if they are explicitly<br /> // set on the Request.<br /> Jar CookieJar
  3. // Timeout specifies a time limit for requests made by this<br /> // Client. The timeout includes connection time, any<br /> // redirects, and reading the response body. The timer remains<br /> // running after Get, Head, Post, or Do return and will<br /> // interrupt reading of the Response.Body.<br /> //<br /> // A Timeout of zero means no timeout.<br /> //<br /> // The Client cancels requests to the underlying Transport<br /> // as if the Request's Context ended.<br /> //<br /> // For compatibility, the Client will also use the deprecated<br /> // CancelRequest method on Transport if found. New<br /> // RoundTripper implementations should use the Request's Context<br /> // for cancellation instead of implementing CancelRequest.<br /> Timeout time.Duration<br />}<br /> A Client is an HTTP client. Its zero value (DefaultClient) is a usable<br /> client that uses DefaultTransport.


客户端是HTTP客户端。它的零值(DefaultClient)是一个可用的使用DefaultTransport的客户端。

The Client’s Transport typically has internal state (cached TCP
connections), so Clients should be reused instead of created as needed.
Clients are safe for concurrent use by multiple goroutines.
客户端的传输通常具有内部状态(缓存TCP)连接),因此应该重用客户端,而不是根据需要创建客户端。多个goroutine并发使用客户端是安全的

  1. A Client is higher-level than a RoundTripper (such as Transport) and<br /> additionally handles HTTP details such as cookies and redirects.<br /> 客户机的级别高于往返程序(如Transport),并且此外,还处理HTTP详细信息,如cookies和重定向。<br />
  2. When following redirects, the Client will forward all headers set on the<br /> initial Request except:<br /> 当执行重定向时,客户端将转发服务器上设置的所有头初始请求,但以下情况除外:
  3. when forwarding sensitive headers like "Authorization",<br /> "WWW-Authenticate", and "Cookie" to untrusted targets. These headers will be<br /> ignored when following a redirect to a domain that is not a subdomain match<br /> or exact match of the initial domain. For example, a redirect from "foo.com"<br /> to either "foo.com" or "sub.foo.com" will forward the sensitive headers, but<br /> a redirect to "bar.com" will not.<br /> •转发敏感标题(如“授权”)时,<br /> WWW验证”和“Cookie”到不受信任的目标。这些标题将被删除在重定向到非子域匹配的域时忽略或初始域的精确匹配。例如,来自“foo.com”的重定向<br /> 到“foo.com”或“sub.foo.com”将转发敏感头,但无法重定向到“bar.com”。
  4. when forwarding the "Cookie" header with a non-nil cookie Jar. Since each<br /> redirect may mutate the state of the cookie jar, a redirect may possibly<br /> alter a cookie set in the initial request. When forwarding the "Cookie"<br /> header, any mutated cookies will be omitted, with the expectation that the<br /> Jar will insert those mutated cookies with the updated values (assuming the<br /> origin matches). If Jar is nil, the initial cookies are forwarded without<br /> change.<br /> <br /> •使用非零Cookie Jar转发“Cookie”标头时。<br /> 自此重定向可能会改变cookie jar的状态,重定向可能会更改初始请求中的cookie集。转发“Cookie”时任何变异的cookie都将被忽略,期望Jar将插入那些带有更新值 的变异cookie(假设原产地匹配)。如果Jarnil,则会转发初始cookie,而不发送改变
  1. func (c *Client) CloseIdleConnections()
  2. func (c *Client) Do(req *Request) (*Response, error)
  3. func (c *Client) Get(url string) (resp *Response, err error)
  4. func (c *Client) Head(url string) (resp *Response, err error)
  5. func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
  6. func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

文档地址: https://pkg.go.dev/net/http#Client

1、Client的6个方法解析

基于Client的6个方法

1.1、func (c *Client) CloseIdleConnections()

CloseldleConnections方法是关闭通信上的所有链接,如果目前有连载在使用,则不会中断;

参数说明

1.2、func (c *Client) Do(req _Request) (_Response, error)

  1. Do方法发送http请求,并返回http响应,遵循客户端的配置策略(例如重定向、cookie、身份验证),如果在执行Do方法时由于策略(CheckRedirect)或者无法使用http(网络链接问题)倒是失败时,会返回错误。<br /> 如果返回的错误为nil,则Response将包含一个非nil Body,需要关闭它,如果Body没有读取到EOF和关闭,那客户端的底层RoundTripper(通常是Transport)可能无法为后续的“keep-alive”请求<br /> 请求时,如果返回值不为nil,将被底层传输关闭,就算有错误。<br /> 通常使用,会用GetPostPostForm代替Do
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "os"
  9. "strings"
  10. )
  11. client := &http.Client{
  12. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  13. return http.ErrUseLastResponse
  14. },
  15. }
  16. RequestAction, err := http.NewRequest(method, url, RequestsParameters)
  17. if err != nil {
  18. fmt.Println(err)
  19. return err
  20. }
  21. RequestAction.Header.Add("Content-Type", "application/json")
  22. res, err := client.Do(RequestAction)
  23. if err != nil {
  24. return err
  25. }
  26. defer res.Body.Close()
  27. body, err := ioutil.ReadAll(res.Body)
  28. if err != nil {
  29. return err
  30. }

参数说明

1.3、func (c Client) Get(url string) (resp Response, err error)

Get方法向执行的url发起GET请求,再根据响应时的响应码进行处理,如果时如下重定向代码之一,则GET请求在调用client的CheckRedirect函数跟随重定向
301(永久移动)
302(找到)
303(见其他)
307(临时重定向)
308(永久重定向)
如果客户端的checkRedirect函数失败或者存在htto协议错误,则会返回错误,非2xx的响应不会导致错误,任何返回的错误都是 *url.Error类型。
如果请求超时,url.Error值的Timeout方法将报告true。
当err为nil时,resp总是包含一个非nil的resp.Body,完成读取后,调用者应关闭resp.Body, 要使用自定义表头发出请求,请使用NewRequest和Client.Do方法。
要使用指定的 context.Context 发出请求,请使用 NewRequestWithContext 和 Client.Do。

参数说明

1.4、func (c Client) Head(url string) (resp Response, err error)

func (c Client ) Head(url string ) (resp Response , err error )
Head 向指定的 URL 发出 HEAD。如果响应是以下重定向代码之一,则 Head 在调用 Client 的 CheckRedirect 函数后跟随重定向:
301(永久移动)
302(找到)
303(见其他)
307(临时重定向)
308(永久重定向)
要使用指定的 context.Context 发出请求,请使用 NewRequestWithContext 和 Client.Do。

1.5、func (c Client) Post(url, contentType string, body io.Reader) (resp Response, err error)

Post 向指定的 URL 发出 POST。
完成读取后,调用者应关闭 resp.Body。
如果提供的主体是 io.Closer,则在请求后关闭。
要设置自定义标头,请使用 NewRequest 和 Client.Do。
要使用指定的 context.Context 发出请求,请使用 NewRequestWithContext 和 Client.Do。
有关如何处理重定向的详细信息,请参阅 Client.Do 方法文档。

1.6、func (c Client) PostForm(url string, data url.Values) (resp Response, err error)

  1. PostForm向指定的URL发出POST,数据的键和值URL编码为请求正文,Content-Type标头设置为application/x-www-form-urlencoded,设置其他标头<br />使用NewRequestClient.Do方法。<br />当errnil时,resp总是包含一个非nilresp.Body,完成读取后,调用者应关闭resp.Body。<br />要使用指定的 context.Context 发出请求,请使用 NewRequestWithContext Client.Do