func requstByParamsGet(){
requst, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
if err != nil {
fmt.Println("ss")
}
params := make(url.Values)
params.Add("name", "kaiyue")
params.Add("age", "18")
//encode之后会生成如下,name=kaiyue&age=18
requst.URL.RawQuery = params.Encode()
r, err := http.DefaultClient.Do(requst)
if err != nil {
fmt.Println("ss")
}
defer r.Body.Close()
printBody(r)
}
func requstByParamsPost(){
requst, err := http.NewRequest(http.MethodPost, "http://httpbin.org/post", nil)
if err != nil {
fmt.Println("ss")
}
params := make(url.Values)
params.Add("name", "kaiyue")
params.Add("age", "18")
//encode之后会生成如下,name=kaiyue&age=18, 是组成url问号后边的参数
requst.URL.RawQuery = params.Encode()
r, err := http.DefaultClient.Do(requst)
if err != nil {
fmt.Println("ss")
}
defer r.Body.Close()
printBody(r)
}
func main() {
requstByParamsPost()
}
结果:
{
"args": {
"age": "18",
"name": "kaiyue"
},
"data": "",
"files": {
},
"form": {
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "0",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1",
"X-Amzn-Trace-Id": "Root=1-6544e26c-2a47c0392e3351a71259c068"
},
"json": null,
"origin": "120.244.60.192",
"url": "http://httpbin.org/post?age=18&name=kaiyue"
}
func requstByHeader(){
requst, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
if err != nil {
fmt.Println("ss")
}
requst.Header.Add("user-agent", "chrome")
r, err := http.DefaultClient.Do(requst)
if err != nil {
fmt.Println("ss")
}
defer r.Body.Close()
printBody(r)
}
func main() {
requstByHeader()
}
结果:
{
"args": {
},
"headers": {
"Accept-Encoding": "gzip",
"Host": "httpbin.org",
"User-Agent": "chrome",
"X-Amzn-Trace-Id": "Root=1-6544e394-14143f26584a7eed32728fd7"
},
"origin": "120.244.60.192",
"url": "http://httpbin.org/get"
}
可以看到其中头部信息已经打印出自己增加的部分内容
更多【golang-【二、http】go的http基本请求设置(设置查询参数、定制请求头)get和post类似】相关视频教程:www.yxfzedu.com