// testHttpGetPost project main.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
. "github.com/soekchl/myUtils"
)
const (
source_url = "https://www.baidu.com"
)
func main() {
httpGet()
HttpPost()
}
func httpGet() {
response, err := http.Get(source_url)
if err != nil {
Error(err)
return
}
if response.Body != nil {
defer response.Body.Close()
}
body, err := ioutil.ReadAll(response.Body)
if response.StatusCode != 200 {
Error("網站獲取錯誤!")
return
}
Notice("獲取內容爲:", string(body))
}
func HttpPost() {
data_str := fmt.Sprintf("name=%s&id=%v", "Luke", 1)
resp, err := http.Post(source_url, "application/x-www-form-urlencoded",
strings.NewReader(data_str))
if err != nil {
Error(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
Error(err)
return
}
if strings.Contains(string(body), "Successful") { // 這是按照post方法的 自定義返回值判斷
Notice("數據發送成功!")
} else {
Error("數據發送失敗!!!", string(body))
}
}
Golang http Get 和 Post
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.