go post请求常用的几种方式

原文链接

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
func httpPost() {
resp, err := http.Post("https://www.abcd123.top/api/v1/login",
"application/x-www-form-urlencoded",
strings.NewReader("username=test&password=ab123123"))
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("https://www.denlery.top/api/v1/login",
url.Values{"username": {"auto"}, "password": {"auto123123"}})
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 httpPostJson() {
jsonStr :=[]byte(`{ "username": "auto", "password": "auto123123" }`)
url:= "https://www.denlery.top/api/v1/login"
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 {
// handle error
}
defer resp.Body.Close()

statuscode := resp.StatusCode
hea := resp.Header
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
fmt.Println(statuscode)
fmt.Println(hea)

}

-------------本文结束 感谢阅读-------------