go 傳送http請求
阿新 • • 發佈:2021-11-23
普通的get請求
package main import ( "io/ioutil" "fmt" "net/http" ) func main() { res,_ :=http.Get("https://www.baidu.com/") defer res.Body.Close() body,_ := ioutil.ReadAll(res.Body) fmt.Print(body) }
帶引數的get請求(引數不放在url裡)
package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func main(){ params := url.Values{} Url, _:= url.Parse("https://www.baidu.com/") params.Set("name","zhaofan") params.Set("age","23") //如果引數中有中文引數,這個方法會進行URLEncode Url.RawQuery = params.Encode() urlPath := Url.String() fmt.Println(urlPath) //等同於https://www.xxx.com?age=23&name=zhaofan resp,_ := http.Get(urlPath) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
get請求新增請求頭
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} req,_ := http.NewRequest("GET","http://www.xxx.com",nil) req.Header.Add("name","zhaofan") req.Header.Add("age","3") resp,_ := client.Do(req)
defer resp.Body.close() body, _ := ioutil.ReadAll(resp.Body) fmt.Printf(string(body)) }
post請求
package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func main() { urlValues := url.Values{} urlValues.Add("name","zhaofan") urlValues.Add("age","22") resp, _ := http.PostForm("http://www.xxx.com",urlValues)
defer resp.Body.close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
post請求的另一種方式
package main import ( "fmt" "io/ioutil" "net/http" "net/url" "strings" ) func main() { urlValues := url.Values{ "name":{"zhaofan"}, "age":{"23"}, } reqBody:= urlValues.Encode() resp, _ := http.Post("http://www.xxx.com/post", "text/html",strings.NewReader(reqBody))
defer resp.Body.close() body,_:= ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
post請求傳送json資料
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} data := make(map[string]interface{}) data["name"] = "zhaofan" data["age"] = "23" bytesData, _ := json.Marshal(data) req, _ := http.NewRequest("POST","http://www.xxx.com",bytes.NewReader(bytesData)) resp, _ := client.Do(req)
defer resp.Body.close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
不用client
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { data := make(map[string]interface{}) data["name"] = "zhaofan" data["age"] = "23" bytesData, _ := json.Marshal(data) resp, _ := http.Post("http://www.xxx.com","application/json", bytes.NewReader(bytesData))
defer resp.Body.close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
說白了,我們記住http.get 和http.post就可以了