go发送POST请求
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) type Payload struct { Name string `json:"name"` Age int `json:"age"` } func main() { // 创建 JSON 数据 payload := Payload{ Name: "John Doe", Age: 30, } // 将结构体转换为 JSON 字符串 jsonData, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshalling JSON:", err) return } // 创建请求的 URL url := "http://example.com/api" // 创建请求 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Println("Error creating request:", err) return } // 设置请求头,指定发送的数据是 JSON 格式 req.Header.Set("Content-Type", "application/json") // 发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() // 打印响应状态码 fmt.Println("Response Status Code:", resp.StatusCode) // 打印响应体 body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println("Response Body:", string(body)) }
本文作者:Jikefan
本文链接:https://www.cnblogs.com/jikefan/articles/18298362
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。