golang用内置包 net/http 发起 get/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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func httpGet() {
resp, err := http.Get("http://www.baidu.com")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPost() {
resp, err := http.Post("http://www.baidu.com",
"application/x-www-form-urlencoded",
strings.NewReader("name=baidu"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostForm() {
resp, err := http.PostForm("http://www.baidu.com",
url.Values{"key": {"Value"}, "id": {"123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.baidu.com", strings.NewReader("name=baidu"))
if err != nil {
// handle error
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=baidu")
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func main() {
httpGet()
httpPost()
httpPostForm()
httpDo()
}
参考更简单的net/http示例
本文网址: https://golangnote.com/topic/9.html 转摘请注明来源