• get请求
get请求可以直接http.Get方法,非常简单。
func HttpGet() {
resp, err := http.Get("http://www.01happy.com/demo/accept.php?id=1")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
• Post请求
func HttpPost() {
resp, err := http.Post("http://localhost:4000/register",
"application/x-www-form-urlencoded",
strings.NewReader("Name=cjb&Password=123456"))
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))
}
• 复杂的请求
有时需要在请求的时候设置头参数、cookie之类的数据,就可以使用http.Do方法。
func HttpDoClinet() {
client := &http.Client{}
req, err := http.NewRequest("POST",
"http://localhost:4000/login", strings.NewReader("Name=cjb&Password=123456"))
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))