不器小窝 不器小窝
首页
随笔
  • GoLang
  • 前端

    • Vue
    • VuePress
  • 开发工具
  • 系统工具
读吧
  • ToDb (opens new window)
  • goKit (opens new window)
  • 友情链接
  • 免费信息
  • 时间线
  • 关于
GitHub (opens new window)

不器

知行合一
首页
随笔
  • GoLang
  • 前端

    • Vue
    • VuePress
  • 开发工具
  • 系统工具
读吧
  • ToDb (opens new window)
  • goKit (opens new window)
  • 友情链接
  • 免费信息
  • 时间线
  • 关于
GitHub (opens new window)
  • GoLang

    • GoLang 安装
    • Go经验
    • 错误集合
    • 基础库

      • flag
      • json
      • log
      • net/http
        • net/http包简介
        • 实现http请求
          • Get
          • Get请求示例
          • 带body参数和Hearder的Get请求
          • Post
          • 带body参数和Hearder的Post请求
      • os
      • sync
      • path
    • 第三方库

    • Fyne

    • Wails

    • GoFrame

  • Dart

  • Markdown

  • 语言
  • GoLang
  • 基础库
不器
2022-06-07
目录

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参数和Hearder的Get请求

net/http包没有封装请求带header的get或者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参数和Hearder的Post请求

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
#GoLang#基础库#http#net
更新时间: 2023/1/30 23:35:37
log
os

← log os→

最近更新
01
Vue-pure-Admin基础
03-16
02
WebStorm工具使用手册
03-15
03
Windows
03-12
更多文章>
Theme by Vdoing | Copyright © 2022-2023 不器 | 小窝
sitemap icon by Icons8
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式