1. get请求
1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "os" 8 ) 9 10 func main() { 11 12 resp, err := http.Get("https://baike.baidu.com/item/书/130176?fr=aladdin") 13 HandleError(err, "http.Get") 14 15 defer resp.Body.Close() 16 17 bytes, e := ioutil.ReadAll(resp.Body) 18 HandleError(e, "outil.ReadAll") 19 20 fmt.Println("get:", string(bytes)) 21 22 } 23 24 func HandleError(err error, when string) { 25 if err != nil { 26 fmt.Println(err, "net.Listen") 27 os.Exit(1) 28 29 } 30 }
2. post请求
1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "os" 8 "strings" 9 ) 10 11 func main() { 12 13 url := "https://httpbin.org/post?name=love" 14 //携带的数据类型,表单 15 resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader("rmb=0.5&hobby=love")) 16 HandleError(err, "htp.post") 17 defer resp.Body.Close() 18 19 bytes, e := ioutil.ReadAll(resp.Body) 20 HandleError(e, "ioutil.ReadAll") 21 fmt.Println(string(bytes)) 22 23 } 24 25 func HandleError(err error, when string) { 26 if err != nil { 27 fmt.Println(err, "net.Listen") 28 os.Exit(1) 29 30 } 31 }