Posted on 04 Jun 2018
GO之HTTP操作
GET
resp, err := http.Get("http://www.test.local")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
POST
-
http.Post
resp, err := http.Post("http://www.test.local", "application/x-www-form-urlencoded", strings.NewReader("name=cjb")) if err != nil { fmt.Println(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
-
http.PostForm
resp, err := http.PostForm("http://www.test.local", url.Values{"key": {"Value"}, "id": {"123"}}) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
自定义请求
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.test.local", strings.NewReader("name=cjb"))
if err != nil {
// handle error
}
req.Header.Set("User-Agent", "myClient")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=anny")
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))