使用http.Post发送JSON数据或http.PostForm提交表单,复杂请求则用http.NewRequest配合http.Client自定义头、超时等;需正确设置Content-Type并关闭响应体防止泄漏。

在Golang中使用net/http发送POST请求非常常见,通常用于向服务器提交数据。你可以通过http.Post或更灵活的http.NewRequest配合http.Client.Do来实现。
如果你只需要发送简单的表单数据或JSON,并且不需要自定义太多请求头,可以直接使用http.Post函数。
示例:发送JSON数据
jsonData := []byte(`{"name":"Alice","age":25}`)
resp, err := http.Post("https://www.php.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>这里第三个参数是io.Reader类型,所以可以用bytes.NewBuffer包装字节数组。
立即学习“go语言免费学习笔记(深入)”;
当你需要设置请求头、超时、Cookie或其他选项时,建议使用http.NewRequest和http.Client。
示例:带自定义Header的POST请求
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>这种方式可以自由控制请求的所有细节,比如认证、压缩、User-Agent等。
对于提交表单,可以使用url.Values来编码数据。
data := url.Values{}
data.Set("username", "alice")
data.Set("password", "secret")
<p>resp, err := http.PostForm("<a href="https://www.php.cn/link/dc076eb055ef5f8a60a41b6195e9f329">https://www.php.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.PostForm会自动设置正确的Content-Type并编码数据。
基本上就这些。根据你的需求选择合适的方法:简单场景用http.Post或http.PostForm,复杂场景用http.NewRequest加http.Client。关键是要正确设置Content-Type,处理响应体后关闭它,避免资源泄漏。
以上就是如何在Golang中使用net/http发送POST请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号