golang 的 http.Post 函数用于向指定的 URL 发送 POST 请求并获取响应。该函数的语法如下:
func Post(url string, contentType string, body io.Reader) (resp *Response, err error)
其中,url 为要请求的 URL 地址,contentType 为请求体的编码格式,body 为请求体内容,类型为 io.Reader。
示例代码:
package main
import (
"bytes"
"fmt"
"net/http"
)
func main() {
url := "http://example.com/post"
// 构造请求体
data := map[string]string{
"username": "test",
"password": "123456",
}
jsonStr := []byte(`{"title":"Buy cheese and bread for breakfast."}`)
reqBody := bytes.NewBuffer(jsonStr)
// 发送 POST 请求
resp, err := http.Post(url, "application/json", reqBody)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// 处理响应
fmt.Println("Status:", resp.Status)
}
在上面的示例中,我们首先构造了一个包含 username 和 password 字段的数据结构,并将其转换为 JSON 格式作为请求体。然后使用 http.Post 函数发送 POST 请求并获取响应。最后打印出响应状态码。