go發送http的get請求
package main
import (
"fmt"
"io/ioutil" //io模塊
"net/http" //http服務模塊
)
func main() {
//go 發送http的get請求
//response, err := http.Get("http://www.baidu.com")
response, err := http.Get("http://o.baidu.com")
//如果發送失敗
if err != nil {
//handle error
fmt.Println("發送get請求報錯了。")
}
//這裡是析構函數關閉body請求
defer response.Body.Close()
//讀取響應的body
body, _ := ioutil.ReadAll(response.Body)
//列印響應的body
fmt.Println(string(body))
}
go發送http的post請求
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
//http post 請求
body := "{\"action\":20}"
res, err := http.Post("https://passport.baidu.com/v2/api/?login", "application/json:charset=utf-8", bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Fatal error", err.Error())
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Fatal error", err.Error())
}
fmt.Println(string(content))
}