GO語言的post請求和get請求方法
阿新 • • 發佈:2019-01-02
首先!剛剛開始接觸GO語言,感覺還是非常強大的,最近在學習中也有很多自己的想法,也嘗試子寫了一些東西,記錄一下加深印象!
標題 GO語言的post請求和get請求
1.post
有兩種 (1)http.postForm
(2)http.post
第一種是一種表單形式的請求,後面可以加上你想附帶的 username,password或者驗證碼
比如這種
var resp *http.Response //ResponseBody := new(ResponseBody) resp, err := http.PostForm("http://localhost/server/index.php?s=/api/user/login", url.Values{"username": {"xkxk"}, "password": {"kxk"}, "v_code": {"123"}}) if err != nil { fmt.Println("POST請求:建立請求失敗", err) } if resp != nil && resp.Body != nil { defer resp.Body.Close() } else { fmt.Println("err ") }
第二種是在裡面設定的
¥¥¥¥重點來了¥¥¥¥
使用這個方法的話,第二個引數要設定成”application/x-www-form-urlencoded”,否則post引數無法傳遞。
func httpPost() { resp, err := http.Post("http://www.01happy.com/demo/accept.php", "application/x-www-form-urlencoded", strings.NewReader("name=cjb")) 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)) }
2.get
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)) }
當然最後還有一點,就是最麻煩的,我們在請求的時候想設定一些引數怎麼辦呢
比如 我做過的一個需求 需要用cookie去請求一個列表這個時候看這裡
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.showdoc.cc", strings.NewReader("name=cjb"))
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))
}
用 req.Header.Set方法 可以把你想傳進去的值 傳進去
(哈哈,最後最後,歡迎大佬來指點錯誤,一起交流,一起學習!)