package main import ( "fmt" "io/ioutil" "net/http" "os" "strings" ) func GET() { client := &http.Client{} reqest, err := http.NewRequest("GET", "http://www.baidu.com/", nil) //建立一个请求 if err != nil { fmt.Println("Fatal error ", err.Error()) os.Exit(0) } //Add 头协议 reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6") reqest.Header.Add("Connection", "keep-alive") reqest.Header.Add("Cookie", "设置cookie") reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0") response, err := client.Do(reqest) //提交 defer response.Body.Close() cookies := response.Cookies() //遍历cookies for _, cookie := range cookies { fmt.Println("cookie:", cookie) } body, err1 := ioutil.ReadAll(response.Body) if err1 != nil { // handle error } fmt.Println(string(body)) //网页源码 } func post() { client := &http.Client{} req, err := http.NewRequest("POST", "http://xxxxx", strings.NewReader("name=1&age=2")) if err != nil { // handle error } reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6") reqest.Header.Add("Connection", "keep-alive") reqest.Header.Add("Cookie", "设置cookie") reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0") resp, err := client.Do(req) cookies := resp.Cookies() for _, cookie := range cookies { fmt.Println("cookie:", cookie) } defer resp.Body.Close() _, err1 := ioutil.ReadAll(resp.Body) if err1 != nil { // handle error } fmt.Println(string(body)) } func main() { GET() }
有疑问加站长微信联系(非本文作者)