golang语言发送json格式的http请求

博客主要介绍了Golang语言发送JSON格式的HTTP请求。内容包括发送普通GET请求、以JSON为参数的POST请求,POST请求可通过字符串拼写或struct转化实现,还介绍了使用struct对返回的JSON结果进行解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

golang语言发送json格式的http请求

 

1、发送普通的GET请求

func testGet() {

url := "https://baidu.com"

req, err := http.NewRequest("GET", url, nil)

client := &http.Client{}

resp, err := client.Do(req)

if err != nil {

panic(err)

}

defer resp.Body.Close()

fmt.Println("response Status:", resp.Status)

fmt.Println("response Headers:", resp.Header)

body, _ := ioutil.ReadAll(resp.Body)

fmt.Println("response Body:", string(body))

}

 

返回结果:

response Status: 200 OK

response Headers: map[Content-Type:[text/html] Vary:[Accept-Encoding] ]

response Body: <!DOCTYPE html>

 

2、发送json为参数的post请求

 

可以直接用字符串拼写出json格式

func testPost(id int, name string) {

requestBody := fmt.Sprintf(`{

"id":%d",

"name": "%s"

}`, id, name)

var jsonStr = []byte(requestBody)

url := "https://test.com"

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

req.Header.Set("Content-Type", "application/json")

client := &http.Client{}

resp, err := client.Do(req)

if err != nil {

panic(err)

}

defer resp.Body.Close()



fmt.Println("response Status:", resp.Status)

fmt.Println("response Headers:", resp.Header)

body, _ := ioutil.ReadAll(resp.Body)

fmt.Println("response Body:", string(body))

}

 

也可以用struct进行转化,比如这样

type RequestBody struct {

Id int `json:"id"`

Name string `json:"name"`

}



func testPost(id int, name string) {

request := RequestBody{

Id: id,

Name: name,

}

requestBody := new(bytes.Buffer)

json.NewEncoder(requestBody).Encode(request)

url := "https://test.com"

req, err := http.NewRequest("POST", url, requestBody)

req.Header.Set("Content-Type", "application/json")

client := &http.Client{}

resp, err := client.Do(req)

if err != nil {

panic(err)

}

defer resp.Body.Close()



fmt.Println("response Status:", resp.Status)

fmt.Println("response Headers:", resp.Header)

body, _ := ioutil.ReadAll(resp.Body)

fmt.Println("response Body:", string(body))

}

 

 3、对返回的json结果进行解析

 

同样是使用struct进行解析,例如返回的json为

{

"id": 1,

"name": "zhangsan"

}

 

则对应的代码为

type UserInfo struct {

Id string `json:"id"`

Name string `json:"name"`

}



func ParseResponse(input string) [] UserInfo {

var user UserInfo

if err := json.Unmarshal([]byte(string(input)), &user); err == nil {

fmt.Println(user.Id)

fmt.Println(user.Name)

} else {

fmt.Println(err)

}

}

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值