关于golang:Golang-常见的-Http-Post-Get请求

9次阅读

共计 1739 个字符,预计需要花费 5 分钟才能阅读完成。

总结下应用 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)
}
正文完
 0