hapiman / jsrice

A common utils using in javascript
0 stars 0 forks source link

Golang中HTTP请求 #47

Open hapiman opened 6 years ago

hapiman commented 6 years ago

基本请求

func httpDo() {
    client := &http.Client{}

    req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", 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 
        // 读取到[]byte数据,通过gjson可以直接取值
    }

    fmt.Println(string(body))
}
// POST请求必须使用`  req.Header.Set("Content-Type", "application/x-www-form-urlencoded")`
hapiman commented 6 years ago

简化请求

GET


func httpGet() {
    resp, err := http.Get("http://www.01happy.com/demo/accept.php?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))
}

POST

func httpPost() {
    resp, err := http.Post("http://www.01happy.com/demo/accept.php",
        "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))
}

// POST请求必须设置 `application/x-www-form-urlencoded`

POST(FORM)

// 一站式解决方案

func httpPostForm() {
    resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
        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))

}
hapiman commented 6 years ago

https://www.jianshu.com/p/be3d9cdc680b https://www.jianshu.com/p/16210100d43d https://www.jianshu.com/p/423869b83124