客户端模拟http请求
2013 年 11 月 26 日
导语
在Golang中web开发中net/http是经常用到的包,在这个包中包含了各种请求与响应的方式,下面我会一一进行介绍。
Get请求
不带参数的Get请求
在这个例子中直接使用http.Get()函数,返回一个 *http.Response
类型的变量, ioutil.ReadAll(resp.Body)
将会读取响应后的内容。
func SendSimpleGetRequest() { resp, err := http.Get("https://baidu.com") if err != nil { panic(err) } defer resp.Body.Close() s, err := ioutil.ReadAll(resp.Body) fmt.Printf(string(s)) }
携带参数的Get请求
这个例子中使用 url.Values{}
返回一个 map[string][]string
类型,用来存放我们的参数,当然也可以直接在url地址中直接携带,但一般不推荐这么使用, params.Encode()
将会对我们的中文进行编码,防止数据传输过程中出错。
func SendComplexGetRequest() { params := url.Values{} Url, err := url.Parse("http://baidu.com?fd=fdsf") if err != nil { panic(err.Error()) } params.Set("a", "fdfds") params.Set("id", string("1")) //如果参数中有中文参数,这个方法会进行URLEncode Url.RawQuery = params.Encode() urlPath := Url.String() resp, err := http.Get(urlPath) defer resp.Body.Close() s, err := ioutil.ReadAll(resp.Body) fmt.Println(string(s)) }
Post请求
一般post请求的参数不会直接在url地址中被看到,同样我们也使用相同的方式追加参数。如下
func httpPostForm() { // params:=url.Values{} // params.Set("hello","fdsfs") //这两种都可以 params := url.Values{"key": {"Value"}, "id": {"123"}} resp, _ := http.PostForm("http://baidu.com", params) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
客户端通用模式
那可能会有小伙伴问,这么多方式该怎么记得住,其实在发送请求时还有一个通用的思路,就是使用客户端,在Golang中我们可以自定义自己的http请求客户端,让它为我们发送http请求。下面的函数中我们同样使用 url.Values{}
存放我们的参数,使用 http.Client{}
实例化一个客户端,使用 http.NewRequest()
新创建一个请求,注意里面的参数全部是自己设置的,当然我们也可以设置成GET方式。req.Header.Set()设置头,最后使用 client.Do(req)
就可以发送请求了。
func httpDo() { client := &http.Client{} urlmap := url.Values{} urlmap.Add("client_id", "esss") urlmap.Add("client_secret", "sk") parms := ioutil.NopCloser(strings.NewReader(urlmap.Encode())) //把form数据编下码 req, err := http.NewRequest("POST", "www.baidu.com", parms) if err != nil { // handle error } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Cookie", "name=anny") resp, err := client.Do(req) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body)) }