Go标准库之net-http-client

Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type Client struct {
//transport指定了单个http请求的机制,如果为nil则会使用DefaultTransport
Transport RoundTripper
//CheckRedirect 指定处理重定向的策略
CheckRedirect func(req *Request, via []*Request) error
//Jar 指定cookie Jar
Jar CookieJar
//指定超时时间
Timeout time.Duration
}
func (c *Client) Do(req *Request) (*Response, error)
func (c *Client) Get(url string) (resp *Response, err error)
func (c *Client) Head(url string) (resp *Response, err error)
func (c *Client) Post(url string, contentType string, body io.Reader) (resp *Response, err error)
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
func NewRequest(method, url string, body io.Reader) (*Request, error)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//举例 带有超时时间的Get请求
c:=Client{Timeout:time.Second}
res,err:=c.Get("http://test.com")
if err!=nil{
...
}
defer res.Body.Close()
content,err:=ioutil.Readall(res.Body)
fmt.Println(string(content))
...
//更灵活的写法
v := url.Values{}
v.Set("name", "xk")
v.Set("age", "18")
req, err := http.NewRequest("GET", "http://www.baidu.com", strings.NewReader(v.Encode()))
if err != nil {
}
c := http.Client{Timeout: time.Second}
res, err := c.Do(req)
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
fmt.Println(string(content))