使用Go发送HTTP POST请求
    		       		warning:
    		            这篇文章距离上次修改已过438天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)
 
func main() {
    // 创建HTTP请求体
    postBody, _ := json.Marshal(map[string]string{
        "name": "John Doe",
        "age":  "30",
    })
 
    // 将请求体转换为字节序列
    requestBody := bytes.NewBuffer(postBody)
 
    // 发送HTTP POST请求
    resp, err := http.Post("http://example.com/post", "application/json", requestBody)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
 
    // 读取响应体
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
 
    // 打印响应内容
    fmt.Println(string(body))
}这段代码演示了如何在Go中创建一个HTTP POST请求,并发送JSON格式的数据。首先,它创建了一个包含JSON数据的请求体。然后,它使用http.Post函数发送请求,并设置了正确的Content-Type头部。最后,它读取并打印了响应体。
评论已关闭