import ( "fmt" "io/ioutil" "net/http" "net/url" "strings" ) func httpGet() { resp, err := http.Get("http://www.baidu.com") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body)) } func httpPost() { resp, err := http.Post("http://www.baidu.com", "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)) } func httpPostForm() { resp, err := http.PostForm("http://www.baidu.com", 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)) } func httpDo() { client := &http.Client{} req, err := http.NewRequest("POST", "http://www.baidu.com", strings.NewReader("name=cjb")) if err != nil { // handle error } 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)) } func main() { httpGet() //httpPost() //httpPostForm() //httpDo() }
复杂的请求(要设置http的header的属性等等)用httpDo方法,其它场合用get,post,postform就可以咯
golang中文网net/http包的详解:http://studygolang.com/articles/2680
时间: 2024-10-03 22:48:31