BoyChai's Blog - put
https://blog.boychai.xyz/index.php/tag/put/
-
[Go]发送GET、POST、DELETE、PUT请求
https://blog.boychai.xyz/index.php/archives/42/
2022-12-07T14:45:00+00:00
GET请求func main() {
// 发送请求
r, err := http.Get("https://www.baidu.com?name=boychai&age=18")
// 检查错误
if err != nil {
panic(err)
}
// 释放
defer func() { _ = r.Body.Close() }()
//读取请求内容
content, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
fmt.Println(string(content))
}POST请求func main() {
// 发送请求
r, err := http.Post("https://www.baidu.com", "", nil)
// 检查错误
if err != nil {
panic(err)
}
// 释放
defer func() { _ = r.Body.Close() }()
//读取请求内容
content, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
fmt.Println(string(content))
}提交FROM表单func main() {
// from data 形式类似于 name=boychai&age=18
data := make(url.Values)
data.Add("name", "boychai")
data.Add("age", "18")
payload := data.Encode()
// 发送请求
r, err := http.Post("https://httpbin.org/post", "application/x-www-form-urlencoded", strings.NewReader(payload))
defer func() { _ = r.Body.Close() }()
if err != nil {
print(err)
}
//读取
content, err := ioutil.ReadAll(r.Body)
fmt.Println(string(content))
}提交JSON数据func main() {
u := struct {
Name string `json:"name"`
Age string `json:"age"`
}{
Name: "BoyChai",
Age: "18",
}
payload, _ := json.Marshal(u)
// 发送请求
r, err := http.Post("https://httpbin.org/post", "application/json", bytes.NewReader(payload))
defer func() { _ = r.Body.Close() }()
if err != nil {
print(err)
}
//读取
content, err := ioutil.ReadAll(r.Body)
fmt.Println(string(content))
}DELETE请求func main() {
// 创建请求对象
request, err := http.NewRequest(http.MethodDelete, "https://www.baidu.com", nil)
if err != nil {
panic(err)
}
// 发送请求
r, err := http.DefaultClient.Do(request)
defer func() { _ = r.Body.Close() }()
if err != nil {
panic(err)
}
// 读取
content, err := ioutil.ReadAll(r.Body)
fmt.Println(string(content))
}PUT请求func main() {
// 创建请求对象
request, err := http.NewRequest(http.MethodPut, "https://www.baidu.com", nil)
if err != nil {
panic(err)
}
// 发送请求
r, err := http.DefaultClient.Do(request)
defer func() { _ = r.Body.Close() }()
if err != nil {
panic(err)
}
// 读取
content, err := ioutil.ReadAll(r.Body)
fmt.Println(string(content))
}