golang如何用http.NewRequest创建get和post请求

在Go语言中,使用http.NewRequest函数可以创建GET和POST请求。下面是一个示例代码,演示如何使用http.NewRequest创建GET和POST请求:

go 复制代码
package main

import (
 "fmt"
 "io/ioutil"
 "net/http"
)

func main() {
 // 创建GET请求
 getRequest, err := http.NewRequest("GET", "https://api.example.com/data", nil)
 if err != nil {
 fmt.Println("创建GET请求失败:", err)
 return
 }

 // 发送GET请求并获取响应
 client := &http.Client{}
 getResponse, err := client.Do(getRequest)
 if err != nil {
 fmt.Println("发送GET请求失败:", err)
 return
 }
 defer getResponse.Body.Close()

 // 读取GET响应的内容
 getResponseBody, err := ioutil.ReadAll(getResponse.Body)
 if err != nil {
 fmt.Println("读取GET响应失败:", err)
 return
 }

 // 打印GET响应的内容
 fmt.Println(string(getResponseBody))

 // 创建POST请求
 postData := []byte(`{"key1": "value1", "key2": "value2"}`)
 postRequest, err := http.NewRequest("POST", "https://api.example.com/data", bytes.NewBuffer(postData))
 if err != nil {
 fmt.Println("创建POST请求失败:", err)
 return
 }
 postRequest.Header.Set("Content-Type", "application/json") // 设置请求头,指定内容类型为JSON

 // 发送POST请求并获取响应
 postResponse, err := client.Do(postRequest)
 if err != nil {
 fmt.Println("发送POST请求失败:", err)
 return
 }
 defer postResponse.Body.Close()

 // 读取POST响应的内容
 postResponseBody, err := ioutil.ReadAll(postResponse.Body)
 if err != nil {
 fmt.Println("读取POST响应失败:", err)
 return
 }

 // 打印POST响应的内容
 fmt.Println(string(postResponseBody))
}

在上述示例中,我们首先创建了一个GET请求,指定了请求的URL为"https://api.example.com/data"。然后,我们使用http.Client类型的客户端发送该请求,并获取响应。对于POST请求,我们创建了一个包含JSON数据的请求主体,并设置了请求头的"Content-Type"字段为"application/json"。然后,我们使用相同的客户端发送该请求,并获取响应。最后,我们读取并打印了GET和POST响应的内容。

相关推荐
拷贝码农卡卡东19 小时前
pre-commit run --all-files 报错:http.client.RemoteDisconnected
网络·网络协议·http
又菜又爱玩呜呜呜~1 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
cellurw1 天前
Linux下C语言实现HTTP+SQLite3电子元器件查询系统
linux·c语言·http
希望20171 天前
Golang | http/server & Gin框架简述
http·golang·gin
全栈技术负责人1 天前
前端网络性能优化实践:从 HTTP 请求到 HTTPS 与 HTTP/2 升级
前端·网络·http
Whisper_Yu1 天前
计算机网络(一)基础概念
计算机网络·http·https·信息与通信
emojiwoo1 天前
HTTP 状态码背后的逻辑:从请求到响应的完整流程解析(含完整流程图)
网络·网络协议·http
娅娅梨1 天前
HarmonyOS-ArkUI Web控件基础铺垫7-HTTP SSL认证图解 及 Charles抓包原理 及您为什么配置对了也抓不到数据
http·华为·ssl·harmonyos
渡我白衣1 天前
Linux网络:应用层协议http
linux·网络·http