golang post請求常用的幾種方式小結(jié)
更新時間:2021年04月27日 11:15:37 作者:誠寜
這篇文章主要介紹了golang post請求常用的幾種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
post請求常用的幾種方式,記錄一下
func httpPost() { resp, err := http.Post("https://www.abcd123.top/api/v1/login", "application/x-www-form-urlencoded", strings.NewReader("username=test&password=ab123123")) 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)) } func httpPostForm() { resp, err := http.PostForm("https://www.denlery.top/api/v1/login", url.Values{"username": {"auto"}, "password": {"auto123123"}}) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body)) } func httpPostJson() { jsonStr :=[]byte(`{ "username": "auto", "password": "auto123123" }`) url:= "https://www.denlery.top/api/v1/login" req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { // handle error } defer resp.Body.Close() statuscode := resp.StatusCode hea := resp.Header body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) fmt.Println(statuscode) fmt.Println(hea) }
補充:golang中發(fā)送post的json請求
看代碼吧~
package main import ( "encoding/json" "log" "net/http" ) type test_struct struct { Test string } //func test(rw http.ResponseWriter, req *http.Request) { // req.ParseForm() // log.Println(req.Form) // //LOG: map[{"test": "that"}:[]] // var t test_struct // for key, _ := range req.Form { // log.Println(key) // //LOG: {"test": "that"} // err := json.Unmarshal([]byte(key), &t) // if err != nil { // log.Println(err.Error()) // } // } // log.Println(t.Test) // //LOG: that //} func test(rw http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) var t test_struct err := decoder.Decode(&t) if err != nil { panic(err) } log.Println(t.Test) } func main() { http.HandleFunc("/test", test) log.Fatal(http.ListenAndServe(":8082", nil)) }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Golang?手寫一個簡單的并發(fā)任務?manager
這篇文章主要介紹了Golang?手寫一個簡單的并發(fā)任務?manager,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08Golang import本地包和導入問題相關(guān)詳解
這篇文章主要介紹了Golang import本地包和導入問題相關(guān)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02Golang基于JWT與Casbin身份驗證授權(quán)實例詳解
這篇文章主要為大家介紹了Golang基于JWT與Casbin實現(xiàn)身份驗證授權(quán)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08