怎么在Go語言中發(fā)送Get和Post請求

怎么在Go語言中發(fā)送Get和Post請求?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

成都創(chuàng)新互聯(lián)是一家成都網(wǎng)站建設(shè)、成都做網(wǎng)站,提供網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),網(wǎng)站制作,建網(wǎng)站,按需策劃,網(wǎng)站開發(fā)公司,2013年開創(chuàng)至今是互聯(lián)行業(yè)建設(shè)者,服務(wù)者。以提升客戶品牌價(jià)值為核心業(yè)務(wù),全程參與項(xiàng)目的網(wǎng)站策劃設(shè)計(jì)制作,前端開發(fā),后臺程序制作以及后期項(xiàng)目運(yùn)營并提出專業(yè)建議和思路。

GET請求:

GET請求直接將參數(shù)拼接在URL里面,如同下面的示例:

func GetData() {
 client := &http.Client{}
 resp, err := client.Get("http://api.map.baidu.com/place/v2/suggestion?query=廣州市天河區(qū)正佳廣場&region=廣州&city_limit=true&output=json&ak=yX8nC9Qzpckek7lY9gGWmlD4TFcA2tzYx3")
 defer resp.Body.Close()
 body, err := ioutil.ReadAll(resp.Body)
 if err != nil {
  fmt.Println(err)
 }
 fmt.Println(string(body))
}

POST請求

Post相關(guān)的請求有三種,分別是:http.post、http.postForm、http.Do請求。

http.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))
}

注意:請求里面的第二個參數(shù)必須帶,否則會報(bào)錯的。

http.postForm:

func PostData() {
 //client := &http.Client{}
 resp, err := http.PostForm("https://www.pgyer.com/apiv2/app/view", url.Values{"appKey": {"62c99290f0cb2c567cb153c1fba75d867e"},
  "_api_key": {"584f29517115df2034348b0c06b3dc57"}, "buildKey": {"22d4944d06354c8dcfb16c4285d04e41"}})
 defer resp.Body.Close()
 body, err := ioutil.ReadAll(resp.Body)
 if err != nil {
  fmt.Println(err)
 }
 fmt.Println(string(body))

}

對于比較復(fù)雜的http請求,我們可以用到http.do的方式進(jìn)行請求

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
 }
 
 fmt.Println(string(body))
}

關(guān)于怎么在Go語言中發(fā)送Get和Post請求問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

網(wǎng)頁標(biāo)題:怎么在Go語言中發(fā)送Get和Post請求
網(wǎng)站地址:http://muchs.cn/article30/pdpdso.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)App開發(fā)、軟件開發(fā)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名