golang使用http client發起get和post請求示例

get請求
get請求可以直接http.Get方法,非常簡單。
func httpGet() {

    var getStr = ""
    for k, v := range data {
        getStr = getStr + k + "=" + v + "&"
    }

    if len(getStr) > 0 {
        getStr = getStr[0 : len(getStr)-1]
    }

    resp, err := http.Get(API_URL + "?" + getStr)

    if resp.StatusCode == http.StatusOK {
        bodyBytes, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        bodyString := string(bodyBytes)

        c.JSON(http.StatusOK, gin.H{
            "data": bodyString,
            "msg":  "success",
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "data": false,
            "msg":  "http status error",
        })
    }
}
}

post請求
一種是使用http.Post方式
func httpPost() {
    resp, err := http.Post(API_URL,
        "application/x-www-form-urlencoded", strings.NewReader("name=cjb"))

    if resp.StatusCode == http.StatusOK {
        bodyBytes, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        bodyString := string(bodyBytes)
        c.JSON(http.StatusOK, gin.H{
            "data": bodyString,
            "msg":  "success",
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "data": false,
            "msg":  "http status error",
        })
    }
}
Tips:使用這個方法的話,第二個參數要設置成”application/x-www-form-urlencoded”,否則post參數無法傳遞。

一種是使用http.PostForm方法
func httpPostForm() {

    sender := make(url.Values)
    for _, k := range keys {
        sender[k] = []string{data[k]}
    }
    resp, err := http.PostForm(API_URL, sender)
 
    if resp.StatusCode == http.StatusOK {
        bodyBytes, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        bodyString := string(bodyBytes)
        c.JSON(http.StatusOK, gin.H{
            "data": bodyString,
            "msg":  "success",
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "data": false,
            "msg":  "http status error",
        })
    }
 
}
 

arrow
arrow

    狼翔月影 發表在 痞客邦 留言(0) 人氣()