登录
首页 >  Golang >  Go教程

Golang实现HTTP请求:GET与POST教程

时间:2026-01-01 22:21:50 168浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Golang实现HTTP请求:GET与POST示例教程》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

Go标准库net/http包提供并发安全的HTTP客户端,推荐用http.Client配合http.NewRequest发送GET/POST请求,需设置Header、超时及关闭resp.Body;支持JSON和表单提交,并可自定义重定向行为。

如何使用Golang实现HTTP客户端请求_发送GET和POST请求示例

Go语言标准库中的net/http包提供了简洁、高效、并发安全的HTTP客户端支持,无需第三方依赖即可完成GET/POST等常见请求。关键在于正确构造http.Request、设置必要的Header(如Content-Type)、处理响应体并及时关闭Body。

发送GET请求(带查询参数)

使用http.Get最简单,但无法自定义Header或超时;更推荐用http.Client配合http.NewRequest,便于控制细节。

  • url.Values构建查询参数,再拼接到URL后
  • 创建http.Client可设置超时,避免请求永久挂起
  • 务必调用resp.Body.Close()释放连接,否则可能耗尽文件描述符
示例代码:
client := &http.Client{Timeout: 10 * time.Second}
params := url.Values{}
params.Set("q", "golang")
params.Set("page", "1")
urlStr := "https://api.example.com/search?" + params.Encode()
<p>req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "MyApp/1.0")</p><p>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>

发送JSON格式的POST请求

向API提交结构化数据时,通常用application/json类型。需将Go结构体序列化为JSON字节,并设好Header。

  • json.Marshal将struct转为[]byte,直接传入bytes.NewReader()作为Body
  • 必须显式设置Content-Type: application/json
  • 检查resp.StatusCode是否为2xx,避免只看err而忽略业务错误(如400/500)
示例代码:
type LoginReq struct {
    Username string `json:"username"`
    Password string `json:"password"`
}
<p>data := LoginReq{Username: "user", Password: "pass"}
jsonBytes, _ := json.Marshal(data)</p><p>req, _ := http.NewRequest("POST", "<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyero2KedWwoYeYkbqVsJqthaW7ZGmosWuwpoprpa2u3LOifauF0L6IgpiFp7alh7qCm6-cdWe-poWpf42gbbSqu7KCZITfsWaGlZHdvqOHt21t' rel='nofollow'>https://api.example.com/login</a>", bytes.NewReader(jsonBytes))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")</p><p>client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()</p><p>if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Printf("HTTP error: %d", resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
</p>

发送表单数据(x-www-form-urlencoded)

类似HTML表单提交,适用于登录、搜索等场景。使用url.Values编码,Header自动匹配。

  • url.Values{"key": {"value"}}构造数据,调用.Encode()生成字符串
  • Body用strings.NewReader()包装编码后的字符串
  • Header设为application/x-www-form-urlencoded
示例代码:
form := url.Values{}
form.Set("email", "test@example.com")
form.Set("token", "abc123")
<p>req, _ := http.NewRequest("POST", "<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyero2KedWwoYeYkbqVsJqthaW7ZGmosWyGYYmmaqjJprOifauEz757hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Jtt' rel='nofollow'>https://api.example.com/submit</a>", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")</p><p>resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// 后续读取响应...
</p>

处理重定向与错误响应

默认情况下http.Client会自动跟随301/302重定向。如需禁用或自定义逻辑,可设置CheckRedirect函数。

  • 设置Client.CheckRedirecthttp.ErrUseLastResponse可停止重定向
  • 手动检查resp.StatusCode判断是否成功(如仅接受200)
  • resp.Statusresp.Header获取状态文本和响应头信息
禁用重定向示例:
client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse // 停止跳转,返回当前响应
    },
    Timeout: 10 * time.Second,
}

以上就是《Golang实现HTTP请求:GET与POST教程》的详细内容,更多关于的资料请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>