我是靠谱客的博主 开朗过客,这篇文章主要介绍golang的post请求和Get请求示例,现在分享给大家,希望可以做个参考。

发送get请求示例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main   import (     "encoding/json"     "fmt"     "io/ioutil"     "net/http"     "net/url"     "time" )   // 定义返回的响应体 type Response struct {     Params  string            `json:"params"`     Headers map[string]string `json:"headers"`     Origin  string            `json:"origin"`     Url     string            `json:"url"` }   var remoteUrl string = "https://www.baidu.com"   // 获取带参数的http get请求响应数据 func getUrlParse() {     data := url.Values{}     data.Set("username", "乔峰")     data.Set("sex", "male")     u, err := url.ParseRequestURI(remoteUrl)     if err != nil {         fmt.Println(err)     }     u.RawQuery = data.Encode()     fmt.Println(u.RawQuery)     resp, err := http.Get(u.String())     if err != nil {         fmt.Println(err)     }     defer resp.Body.Close() // 一定要关闭释放tcp连接     body, err := ioutil.ReadAll(resp.Body)     if err != nil {         fmt.Println(err)     }     fmt.Println(string(body)) }   // 解析get请求的返回的json结果到struct func getResultToStruct() {     resp, err := http.Get(remoteUrl)     if err != nil {         fmt.Println(err)         return     }     defer resp.Body.Close()     var res Response // 定义res为Responser结构体     body, err := ioutil.ReadAll(resp.Body)     if err != nil {         fmt.Println(err)         return     }     _ = json.Unmarshal(body, &res) // 注意这里是&res 地址引用     fmt.Printf("%#v\n", res) }   //get 请求添加头消息 func getHttpByHeader() {     param := url.Values{}     param.Set("username", "babala")     param.Set("sex", "female")     u, _ := url.ParseRequestURI(remoteUrl)     u.RawQuery = param.Encode() // 把参数转换成 sex=female&username=babala     fmt.Println(u)     //重点注意:如果我们直接使用默认的http,那么它是没有超时时间的。这样就会带来性能问题,具体稍后写一篇详细介绍这块     client := &http.Client{Timeout: 10 * time.Second}     req, err := http.NewRequest("GET", u.String(), nil)     if err != nil {         fmt.Println(err)     }     // 添加请求头header 参数     req.Header.Add("username2", "风清扬")     req.Header.Add("age1", "89")     resp, _ := client.Do(req)     defer resp.Body.Close()     body, err := ioutil.ReadAll(resp.Body)     if err != nil {         panic(err)     }     fmt.Println(string(body))   }   func main() {     getResultToStruct()     getHttpByHeader() }


发送post请求示例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main   import (     "bytes"     "encoding/json"     "fmt"     "io/ioutil"     "net/http"     "net/url"     "strings"     "time" )   var remoteUrl = "https://www.zhoubotong.site"   // 发送表单post请求 func postByForm() {     param := url.Values{}     param.Add("username", "乔峰")     param.Add("sex", "male")     resp, _ := http.PostForm(remoteUrl, param) // 表单提交"Content-Type": "application/x-www-form-urlencoded"     defer resp.Body.Close()     body, _ := ioutil.ReadAll(resp.Body)     fmt.Println(string(body)) }   // 发送表单提交,可以对比上面的postByForm的实现差异 func postByForm2() {     urlValue := url.Values{     "username": {"乔峰"},     "sex":      {"male"}, }     respData := urlValue.Encode()     fmt.Println(respData) // encode转码:name=%E4%B9%94%E5%B3%B0&sex=male     resp, _ := http.Post(remoteUrl, "text/html", strings.NewReader(respData))     //注意接收数据类型为text/html,对应在postman中的x-www-form-urlencoded中的key value参数     defer resp.Body.Close()     body, _ := ioutil.ReadAll(resp.Body)     fmt.Println(string(body)) }   // 发送json数据 func postJson() {     client := &http.Client{Timeout: time.Second * 10}     param := make(map[string]interface{})     param["username"] = "乔峰"     param["sex"] = "male"     respdata, _ := json.Marshal(param) // respdata[]byte类型,转化成string类型便于查看     req, _ := http.NewRequest("POST", remoteUrl, bytes.NewReader(respdata))     //http.NewRequest请求会自动发送header中的Content-Type为applcation/json,对应在postman中的body的raw的json参数     resp, _ := client.Do(req)     body, _ := ioutil.ReadAll(resp.Body)     fmt.Println(string(body)) }   // 发送json数据,注意和上面实现的区别 func postJson2() {     param := make(map[string]interface{})     param["username"] = "乔峰"     param["sex"] = "male"     respdata, _ := json.Marshal(param) // respdata[]byte类型,转化成string类型便于查看     fmt.Println(string(respdata))     resp, _ := http.Post(remoteUrl, "application/json", bytes.NewReader(respdata))     defer resp.Body.Close()     body, _ := ioutil.ReadAll(resp.Body)     fmt.Println(string(body)) }   /* 对应的postman中params中的key value参数,我估计很多人都很迷惑postman工具的params和body两个地方传递参数的区别, 其实Params处设置的变量请求时会url后问号传参(?x=y)。而Body里设置的参数则是接口真正请求时发的参数,下面这个例子就是通过params传参 */ func postString() {     param := url.Values{}     param.Add("username", "babala")     param.Add("sex", "female")     u, _ := url.ParseRequestURI(remoteUrl)     u.RawQuery = param.Encode()     fmt.Println(u)     client := &http.Client{}     req, _ := http.NewRequest("POST", u.String(), nil) // 注意发送数据类似为string的post请求,对应的postman中params中的key value参数     resp, _ := client.Do(req)     defer resp.Body.Close()     body, _ := ioutil.ReadAll(resp.Body)     fmt.Println(string(body)) }   func main() {     //postByForm()     //postByForm2()     //postJson()     //postJson2()     postString()   }

通过上面的示例介绍,涉及了日常开发中各种场景的请求类型,基本满足了常规开发,以上只是示例。

最后

以上就是开朗过客最近收集整理的关于golang的post请求和Get请求示例的全部内容,更多相关golang内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(268)

评论列表共有 0 条评论

立即
投稿
返回
顶部