【笔记】Go语言发送请求

前言

Go语言发送请求

定义响应体结构体

  • 用于将JSON格式的响应体字符串文本转换为响应体结构体
1
2
3
4
type ResponseObject struct {
code uint
data string
}

发送Get请求

  • 通过http.Get()函数发送Get请求

<url>:请求URL

1
2
3
4
5
6
7
8
// 发起请求获取响应
responseEntity, _ := http.Get("<url>")
defer responseEntity.Body.Close()
// 将响应体转换为字符串
responseText, _ := ioutil.ReadAll(responseEntity.Body)
// 将JSON格式的响应体字符串文本转换为响应体结构体
var responseObject ResponseObject
json.Unmarshal(responseText, &responseObject)

发送Post请求

form数据

  • 通过http.Post()函数发送携带form数据的Post请求
1
2
3
4
5
6
7
8
9
10
// 请求体参数
var requestPayload string = "key=value"
// 发起请求获取响应
responseEntity, _ := http.Post("<url>", "application/x-www-form-urlencoded", strings.NewReader(requestPayload))
defer responseEntity.Body.Close()
// 将响应体转换为文本
responseText, _ := ioutil.ReadAll(responseEntity.Body)
// 将JSON格式的响应体文本转换为响应体结构体
var responseObject ResponseObject
json.Unmarshal(responseText, &responseObject)
  • 通过http.PostForm()函数发送携带form数据的Post请求
1
2
3
4
5
6
7
8
9
10
// 请求体参数
requestPayload := url.Values{"key_1": {"value"}, "key_2": {"value"}}
// 发起请求获取响应
responseEntity, _ := http.PostForm("<url>", requestPayload)
defer responseEntity.Body.Close()
// 将响应体转换为文本
responseText, _ := ioutil.ReadAll(responseEntity.Body)
// 将JSON格式的响应体文本转换为响应体结构体
var responseObject ResponseObject
json.Unmarshal(responseText, &responseObject)

json数据

  • 通过http.Post()函数发送携带json数据的Post请求
1
2
3
4
5
6
7
8
9
10
// 请求体参数
var requestPayload string = "{'key':'value'}"
// 发起请求获取响应
responseEntity, _ := http.Post("<url>", "application/json", strings.NewReader(requestPayload))
defer responseEntity.Body.Close()
// 将响应体转换为文本
responseText, _ := ioutil.ReadAll(responseEntity.Body)
// 将JSON格式的响应体文本转换为响应体结构体
var responseObject ResponseObject
json.Unmarshal(responseText, &responseObject)

其他请求

<method>:请求方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 请求体参数
var requestPayload string = "{'key':'value'}"
// 创建请求实体
requestEntity, _ := http.NewRequest("<method>", "<url>", requestPayload)
// 设置请求头
requestEntity.Header.Add("Content-Type", "application/json")
// 发起请求获取响应
responseEntity, _ := http.DefaultClient.Do(requestEntity)
defer responseEntity.Body.Close()
// 将响应体转换为文本
responseText, _ := ioutil.ReadAll(responseEntity.Body)
// 将JSON格式的响应体文本转换为响应体结构体
var responseObject ResponseObject
json.Unmarshal(responseText, &responseObject)

完成

参考文献

腾讯云开发者社区——双鬼带单