如何使用Golang net/http创建HTTP客户端_发送GET和POST请求

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.Clienthttp.NewRequest,GET 通常用快捷方法,POST 则需构造请求体。

发送 GET 请求(简洁方式)

对简单 GET,直接用 http.Get 最方便,它自动处理连接、重定向和基础错误:

  • 返回 *http.Responseerror,记得检查错误并关闭响应体(resp.Body.Close()
  • 响应体需手动读取,常用 io.ReadAlljson.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://www./link/dc076eb055ef5f8a60a41b6195e9f329", 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://www./link/dc076eb055ef5f8a60a41b6195e9f329", bytes.NewReader(jsonBytes)) req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close()