主页 > 知识库 > golang使用http client发起get和post请求示例

golang使用http client发起get和post请求示例

热门标签:AI电销 呼叫中心市场需求 百度竞价排名 服务外包 铁路电话系统 地方门户网站 Linux服务器 网站排名优化

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请求示例》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266