使用http.Post發(fā)送JSON數(shù)據(jù)或http.PostForm提交表單,復(fù)雜請(qǐng)求則用http.NewRequest配合http.Client自定義頭、超時(shí)等;需正確設(shè)置Content-Type并關(guān)閉響應(yīng)體防止泄漏。
在Golang中使用net/http
發(fā)送POST請(qǐng)求非常常見,通常用于向服務(wù)器提交數(shù)據(jù)。你可以通過http.Post
或更靈活的http.NewRequest
配合http.Client.Do
來實(shí)現(xiàn)。
如果你只需要發(fā)送簡單的表單數(shù)據(jù)或JSON,并且不需要自定義太多請(qǐng)求頭,可以直接使用http.Post
函數(shù)。
示例:發(fā)送JSON數(shù)據(jù)
jsonData := []byte(`{"name":"Alice","age":25}`) resp, err := http.Post("http://ipnx.cn/link/dc076eb055ef5f8a60a41b6195e9f329", "application/json", bytes.NewBuffer(jsonData)) if err != nil { log.Fatal(err) } defer resp.Body.Close() <p>body, _ := io.ReadAll(resp.Body) fmt.Println(string(body))</p>
這里第三個(gè)參數(shù)是io.Reader
類型,所以可以用bytes.NewBuffer
包裝字節(jié)數(shù)組。
立即學(xué)習(xí)“go語言免費(fèi)學(xué)習(xí)筆記(深入)”;
當(dāng)你需要設(shè)置請(qǐng)求頭、超時(shí)、Cookie或其他選項(xiàng)時(shí),建議使用http.NewRequest
和http.Client
。
示例:帶自定義Header的POST請(qǐng)求
jsonData := []byte(`{"title":"Hello","body":"World"}`) req, err := http.NewRequest("POST", "https://jsonplaceholder.typicode.com/posts", bytes.NewBuffer(jsonData)) if err != nil { log.Fatal(err) } <p>req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer your-token-here")</p><p>client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close()</p><p>body, _ := io.ReadAll(resp.Body) fmt.Println(string(body))</p>
這種方式可以自由控制請(qǐng)求的所有細(xì)節(jié),比如認(rèn)證、壓縮、User-Agent等。
對(duì)于提交表單,可以使用url.Values
來編碼數(shù)據(jù)。
data := url.Values{} data.Set("username", "alice") data.Set("password", "secret") <p>resp, err := http.PostForm("<a href="http://ipnx.cn/link/dc076eb055ef5f8a60a41b6195e9f329">http://ipnx.cn/link/dc076eb055ef5f8a60a41b6195e9f329</a>", data) if err != nil { log.Fatal(err) } defer resp.Body.Close()</p><p>body, _ := io.ReadAll(resp.Body) fmt.Println(string(body))</p>
http.Post
0會(huì)自動(dòng)設(shè)置正確的Content-Type并編碼數(shù)據(jù)。
基本上就這些。根據(jù)你的需求選擇合適的方法:簡單場景用http.Post
或http.Post
0,復(fù)雜場景用http.NewRequest
加http.Client
。關(guān)鍵是要正確設(shè)置Content-Type,處理響應(yīng)體后關(guān)閉它,避免資源泄漏。
以上就是如何在Golang中使用net/http發(fā)送POST請(qǐng)求的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個(gè)人都需要一臺(tái)速度更快、更穩(wěn)定的 PC。隨著時(shí)間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺(tái)進(jìn)程會(huì)占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)