总结下使用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)
}

goper
413 声望25 粉丝

go 后端开发