在发送的http请求中我们可以定制自己的请求体,下面是几个示例代码
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func printBody(r *http.Response){
content, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
fmt.Printf("%s", content)
}
//设置请求查询参数
func requestByParams(){
request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
if err != nil {
panic(err)
}
params := make(url.Values)
params.Add("name", "yuan")
params.Add("age", "18")
request.URL.RawQuery = params.Encode()
fmt.Println(params.Encode())
resp, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer func() {_ = resp.Body.Close()}()
printBody(resp)
//{
// "args": {
// "age": "18",
// "name": "yuan"
//},
// "headers": {
// "Accept-Encoding": "gzip",
// "Host": "httpbin.org",
// "User-Agent": "Go-http-client/1.1",
// "X-Amzn-Trace-Id": "Root=1-60e46b98-58667aee5367f1aa1ca102c9"
//},
// "origin": "222.211.214.252",
// "url": "http://httpbin.org/get?age=18&name=yuan"
//}
}
//定制请求头
func reauestByHead(){
request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
if err != nil {
panic(err)
}
request.Header.Add("user-agent", "chrome")
resp, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer func() {_ = resp.Body.Close()}()
printBody(resp)
//{
// "args": {},
// "headers": {
// "Accept-Encoding": "gzip",
// "Host": "httpbin.org",
// "User-Agent": "chrome",
// "X-Amzn-Trace-Id": "Root=1-60e46c63-22fd52047229e6175f52166c"
//},
// "origin": "222.211.214.252",
// "url": "http://httpbin.org/get"
//}
}
func main() {
requestByParams()
reauestByHead()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)