Golang发送GET和POST请求教程
时间:2025-12-19
浏览:109
作者:佚名
从现在开始,努力学习吧!本文《Golang net/http发送GET和POST请求教程》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
Go 的 net/http 包提供简洁的 HTTP 请求方法:1. 简单 GET 用 http.Get;2. 自定义需求用 http.Client;3. POST 表单用 url.Values.Encode;4. POST JSON 用 json.Marshal 并设 Content-Type。

使用 Go 的 net/http 包发送 HTTP 请求非常简洁,无需第三方依赖。核心是 http.Client 和 http.NewRequest,GET 通常用快捷方法,POST 则需构造请求体。
发送 GET 请求(简洁方式)
对简单 GET,直接用 http.Get 最方便,它自动处理连接、重定向和基础错误:
- 返回
*http.Response和error,记得检查错误并关闭响应体(resp.Body.Close()) - 响应体需手动读取,常用
io.ReadAll或json.NewDecoder解析
resp, err := http.Get("https://httpbin.org/get")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
发送 GET 请求(自定义 Client 方式)
需要设置超时、代理、Header 或复用连接时,应显式创建 http.Client:
- 通过
http.Client{Timeout: 10 * time.Second}控制请求总时长 - 用
req.Header.Set("User-Agent", "...")添加请求头 - 调用
client.Do(req)发送已构建的请求
client := &http.Client{Timeout: 10 * time.Second}
req, _ := http.NewRequest("GET", "https://httpbin.org/get", nil)
req.Header.Set("User-Agent", "MyApp/1.0")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
发送 POST 请求(表单数据)
提交 application/x-www-form-urlencoded 数据(如登录表单),推荐用 url.Values:
- 调用
url.Values.Encode()得到标准编码字符串 - 设置
Content-Type: application/x-www-form-urlencoded - 将编码后字符串作为
strings.NewReader传入http.NewRequest
data := url.Values{"name": {"Alice"}, "age": {"30"}}
req, _ := http.NewRequest("POST", "https://httpbin.org/post", strings.NewReader(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
发送 POST 请求(JSON 数据)
向 API 提交 JSON,需序列化结构体并设置对应 Header:
- 用
json.Marshal将 map 或 struct 转为字节切片 - 设置
Content-Type: application/json - 用
bytes.NewReader(jsonBytes)构造请求体
payload := map[string]string{"title": "Hello", "content": "World"}
jsonBytes, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", "https://httpbin.org/post", bytes.NewReader(jsonBytes))
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
好了,本文到此结束,带大家了解了《Golang发送GET和POST请求教程》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
