婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > golang使用http client發起get和post請求示例

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

熱門標簽:福州鐵通自動外呼系統 長沙ai機器人電銷 賺地圖標注的錢犯法嗎 地圖標注測試 澳門防封電銷卡 濮陽自動外呼系統代理 廣東語音外呼系統供應商 烏魯木齊人工電銷機器人系統 智能電銷機器人營銷

golang要請求遠程網頁,可以使用net/http包中的client提供的方法實現。查看了官方網站有一些示例,沒有太全面的例子,于是自己整理了一下:

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請求

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

Tips:使用這個方法的話,第二個參數要設置成”application/x-www-form-urlencoded”,否則post參數無法傳遞。

http.PostForm方法

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))

}

復雜的請求

有時需要在請求的時候設置頭參數、cookie之類的數據,就可以使用http.Do方法。

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

同上面的post請求,必須要設定Content-Type為application/x-www-form-urlencoded,post參數才可正常傳遞。

如果要發起head請求可以直接使用http client的head方法,比較簡單,這里就不再說明。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • golang http請求封裝代碼
  • Golang發送http GET請求的示例代碼
  • 詳解golang開發中http請求redirect的問題
  • 詳解golang中發送http請求的幾種常見情況
  • golang編程入門之http請求天氣實例
  • golang高性能的http請求 fasthttp詳解

標簽:西雙版納 慶陽 德州 太原 廣西 阿克蘇 調研邀請 貴陽

巨人網絡通訊聲明:本文標題《golang使用http client發起get和post請求示例》,本文關鍵詞  golang,使用,http,client,發起,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《golang使用http client發起get和post請求示例》相關的同類信息!
  • 本頁收集關于golang使用http client發起get和post請求示例的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 阜南县| 乌拉特中旗| 汉阴县| 梁河县| 天气| 都匀市| 延津县| 垫江县| 博爱县| 井冈山市| 岑溪市| 保靖县| 吉木乃县| 福泉市| 科技| 区。| 莱芜市| 阳谷县| 临泽县| 马尔康县| 宜兰市| 开远市| 民勤县| 三江| 西城区| 信阳市| 广河县| 外汇| 甘泉县| 门头沟区| 徐汇区| 峨眉山市| 忻城县| 阜平县| 潼关县| 建德市| 曲阳县| 民县| 康保县| 新建县| 牟定县|