以下是net/http包中的几种进行http请求的方式:
1. http.Get和http.Post
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// http.Get
func httpGet() {
resp, err := http.Get("http://www.baidu.com")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
func httpPost() {
resp, err := http.Post("http://www.baidu.com",
"application/x-www-form-urlencode",
strings.NewReader("name=abc")) // Content-Type post请求必须设置
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
2. http.Client
// http.Client
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST",
"http://www.baidu.com",
strings.NewReader("name=abc"))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
fmt.Println(string(body))
}