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))
}
posted @ 2024-07-12 14:46  Jikefan  阅读(19)  评论(0)    收藏  举报