格式1

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func main() {
	url:=""
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("接口报错:",err)
		os.Exit(1)
	}
	b, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	if err != nil {
		fmt.Println("接口报错:",err)
		os.Exit(1)
	}
	fmt.Println(string(b))
}

或者

import "net/http"
...
clt := http.Client{}
resp, err := clt.Get("http://wwww.baidu.com")

格式2

package main

import (
	"fmt"
	"strings"
	"net/http"
	"io/ioutil"
)

func main() {
	url := ""
	//参数
	payload := strings.NewReader("")
	req, _ := http.NewRequest("POST", url, payload)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Println(res)
	fmt.Println(string(body))
}

或者

import (
"net/http"
"net/url"
)
...
data := url.Values{"first":{"one"}, "second":{"two"}}
http.PostForm("xxxx", data)

本质

无论是get方法还是post方法,最终是会调用net/http包的NewRequest函数。多种多样的请求形式,也仅仅是封装的不同而已。

1、使用http.NewRequest函数获得request实体

2、利用http.client结构体的Do方法,将request实体传入Do方法中

其中:

func NewReader(s string) *Reader { return &Reader{s, 0, -1} }
strings.NewReader*strings.Reader
resp, err := http.DefaultClient.Do(req)