net包 http - golang

 在上一篇文章中,主要学习了一下dial,主要用于一些tcp或者udp的socket连接。今天我们来看看net包中的http请求。

 在go中,主要给我们封装了4个基础请求让我们可以快速实现http请求,他们分别是:

 http.Get(url string)

 http.Head(url string)

 http.Post(url, contentType string, body io.Reader)

 http.PostFrom(url string, data url.Values)

然后让我们看看他们的关系:

从上图我们可以看出,他们最终都是把请求体通过NewRequest()处理,然后传入c.Do()处理返回。以http.Get为例代码为:

func Get(url string) (resp *Response, err error) {
	return DefaultClient.Get(url)
}


func (c *Client) Get(url string) (resp *Response, err error) {
	req, err := NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	return c.Do(req)
}

其他几个请求大体和这个相似,只不过NewRequest()传入数据不同。具体大家可以自己查看一下源码。

由此可见,我们通过对NewRequest() 和 c.Do() 的调用就可以很简单的实现各种http请求。

下面我们看一下,各个请求的使用方法:

http.Get() 很简单我们只需要填入URL即可,代码如下

    resp, err := http.Get("http://www.e.com/demo?id=1")
    if err != nil {
        // handle error
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

http.Post()  和 http.PostFrom 是一种请求,通过上图我们也可以看出postfrom是对post的进一步封装。我们看看如何postfrom是怎么调用post的:

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
	return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}

http.post()请求为:

    resp, err := http.Post("http://www.aa.com/demo/",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=cjb"))
    if err != nil {
        fmt.Println(err)
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
 
    fmt.Println(string(body))

http.PostFrom()请求为:

resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
        url.Values{"key": {"Value"}, "id": {"123"}})
 
    if err != nil {
        // handle error
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
 
    fmt.Println(string(body))

最后让我们看看如何用newrequest和c.do实现:

postValue := url.Values{
"email": {"[email protected]"},
"password": {"123456"},
}
 
postString := postValue.Encode()
 
req, err := http.NewRequest("POST","http://www.aa.com/demo", strings.NewReader(postString))
if err != nil {
// handle error
}
 
// 表单方式(必须)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
//AJAX 方式请求
req.Header.Add("x-requested-with", "XMLHttpRequest")
 
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
 
defer resp.Body.Close()
 
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
 
fmt.Println(string(body))
发布了48 篇原创文章 · 获赞 17 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/aixinaxc/article/details/88799080