7.3 http客户端(GET、POST、POSTFORM、DO)
示例:
1、实现Get请求方法
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
requestUrl := "http://www.baidu.com"
response, err := http.Get(requestUrl)
if err != nil {
fmt.Println(err)
}
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
2、实现post请求方法
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
requestUrl := "http://www.baidu.com/"
postValue := url.Values{
"username": {"aa"},
"address": {"bb"},
"subject": {"cc"},
"form": {"dd"},
}
//request, err := http.PostForm(requestUrl, postValue)
body := bytes.NewBufferString(postValue.Encode())
request, err := http.Post(requestUrl, "text/html", body)
if err != nil {
fmt.Println(err)
}
defer request.Body.Close()
fmt.Println(request.StatusCode)
if request.StatusCode == 200 {
rb, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Println(rb)
}
fmt.Println(string(rb))
}
}
3、 实现PostForm请求方法
package main
import (
"fmt"
"io/ioutil"
"net/url"
"net/http"
)
func main() {
requestUrl := "http://www.baidu.com/"
postValue := url.Values{
"username": {"aa"},
"address": {"bb"},
"subject": {"cc"},
"form": {"dd"},
}
request, err := http.PostForm(requestUrl, postValue)
if err != nil {
fmt.Println(err)
}
defer request.Body.Close()
fmt.Println(request.StatusCode)
if request.StatusCode == 200 {
rb, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Println(rb)
}
fmt.Println(string(rb))
}
}
4、http.Do
使用http.Do方法可以在请求的时候设置头参数、cookie之类的数据。
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
client := &http.Client{}
request, err := http.NewRequest("GET", "http://www.baidu.com", nil)
if err != nil {
fmt.Println(err)
}
cookie := &http.Cookie{Name: "JERRY", Value: "dkfsf"}
request.AddCookie(cookie) //向request中添加cookie
//设置request的header
request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
response, err := client.Do(request)
if err != nil {
fmt.Println(err)
return
}
defer response.Body.Close()
fmt.Println(response.StatusCode)
if response.StatusCode == 200 {
r, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(r))
}
}
links
- 目录
- 上一节:net/http包使用及工作原理
- 下一节:Request