总结下应用Go 申请, 罕用的几种办法.
func httpGet() { resp, err := http.Get("https://www.baidu.com?id=1") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))}//一种是应用http.Post形式func httpPost() { resp, err := http.Post("https://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))}//一种是应用http.PostForm办法func httpPostForm() { resp, err := http.PostForm("https://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))}//有时须要在申请的时候设置头参数、cookie之类的数据,就能够应用http.Do办法。func httpDo() { client := &http.Client{} req, err := http.NewRequest("POST", "https://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))}//针对登录申请之后, 302 Found func httpPostFound() { client := &http.Transport{} req, err := http.NewRequest("POST", "https://www.baidu.com/login.php", strings.NewReader("act=login&user_name=111&password=1111")) if err != nil { // handle error } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Connection", "Keep-Alive") response, err := client.RoundTrip(req) defer response.Body.Close() var cookie string status := response.Status if status == "302 Found" { cookies := response.Cookies() for _, item := range cookies { if item.Name == "FFPOST" { cookie = item.Value break } } } fmt.Println(cookie)}