Wang's blog Wang's blog
目录

net|http包简介

# net/http包简介

net/http包提供了一个简单的HTTP服务器。有时我们需要对第三方的API进行请求时,可以使用net/http包。

# 实现http请求

# Get

# Get请求示例

package main
import (
	"fmt"
	"io/ioutil"
	"net/http"
)
func main() {
	resp, err := http.Get("http://www.baidu.com/")
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Print(string(body))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#body参数和HearderGet请求

net/http包没有封装请求带headerget或者post方法,所以,要想请求中带header,只能使用NewRequest方法。不带header的请求也可以使用此方法。

package main
import (
	"fmt"
	"io/ioutil"
	"net/http"
)
func main() {
	client := &http.Client{}
	apiURL := "http://127.0.0.1:8080/get"
	req, err := http.NewRequest("GET", apiURL, nil)
	//添加查询参数
	q := req.URL.Query()
	q.Add("username", "admin")
	q.Add("password", "123")
	req.URL.RawQuery = q.Encode()
	fmt.Println(req.URL.String())
	req.Header.Add("Content-Type", "application/json")
	if err != nil {
		fmt.Printf("post failed, err:%v\n\n", err)
		return
	}
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get resp failed,err:%v\n\n", err)
		return
	}
	fmt.Println(string(b))
}
输出:
http://127.0.0.1:8080/get?password=123&username=admin
{"status": "ok"}
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

# Post

#body参数和HearderPost请求

package main
import (
 "fmt"
 "net/http"
 "io/ioutil"
 "strings"
 "encoding/json"
 "log"
)
// OsInfo 系统信息
type OsInfo struct {
	BootTime string //开机时间
	OsName string //系统名称
	Version string //版本信息
	UploadSpeed string //上传速度
	DownloadSpeed string //下载速度
}
func main() {
 url := "http://127.0.0.1:8088/tempapi/osInfo"
 osInfo :=OsInfo{
 BootTime:"2022年03月01日 00:00:00",
 OsName:"darwin",
 Version:"11.6.1",
 UploadSpeed:"503.1KB/s",
 DownloadSpeed:"11.6MB/s",
 }
 jsons,_:=json.Marshal(teamworkinfo)
 result :=string(jsons)
 jsoninfo :=strings.NewReader(result)
 req, _ := http.NewRequest("POST", url,jsoninfo)
 req.Header.Add("appCode", "winner")
 req.Header.Add("token", "466221e4-593d-4bb8-b41b-hcfedhf")//应用对接的token
 req.Header.Add("Content-Type", "application/json")
 res, err := http.DefaultClient.Do(req)
 if err !=nil{
 log.Printf("调用接口异常%v",err.Error())
 }
 defer res.Body.Close()
 body, err := ioutil.ReadAll(res.Body)
 if err !=nil{
 log.Printf("调用接口异常%v",err.Error())
 }
 //fmt.Println(res)
 fmt.Println(string(body))
}
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
编辑 (opens new window)
Theme by Vdoing | Copyright © 2019-2022 Evan Xu | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式

AltStyle によって変換されたページ (->オリジナル) /