golang使用http客户端发起get和post请求示例

  

golang要请求远程网页,可以使用net/http包中的客户提供的方法实现。查看了官方网站有一些示例,没有太全面的例子,于是自己整理了一下:

  

<强>得到请求
  

        func httpGet () {   分别地,犯错:=http.Get (" http://www.01happy.com/demo/accept.php& # 63; id=1”)   如果犯错!=nil {//处理错误   }      推迟resp.Body.Close ()   身体,犯错:=ioutil.ReadAll (resp.Body)   如果犯错!=nil {//处理错误   }      fmt.Println (string(身体))   }      之前      

<强>文章请求
  

  

http。发布方式
  

        func httpPost () {   分别地,犯错:=http.Post (" http://www.01happy.com/demo/accept.php ",   “应用程序/x-www-form-urlencoded”,   strings.NewReader (" name=可"))   如果犯错!=nil {   fmt.Println (err)   }      推迟resp.Body.Close ()   身体,犯错:=ioutil.ReadAll (resp.Body)   如果犯错!=nil {//处理错误   }      fmt.Println (string(身体))   }      

提示:使用这个方法的话,第二个参数要设置成“应用程序/x-www-form-urlencoded”,否则帖子参数无法传递。

  

http。PostForm方法
  

        func httpPostForm () {   分别地,犯错:=http.PostForm (" http://www.01happy.com/demo/accept.php ",   url。值{“关键”:{Value}, " id ": {" 123 "}})      如果犯错!=nil {//处理错误   }      推迟resp.Body.Close ()   身体,犯错:=ioutil.ReadAll (resp.Body)   如果犯错!=nil {//处理错误   }      fmt.Println (string(身体))      }      

<强>复杂的请求
  

  

有时需要在请求的时候设置头参数,饼干之类的数据,就可以使用http.Do方法。

        func httpDo () {   客户:=,http.Client {}      http请求,犯错:=ewRequest(“文章”、“http://www.01happy.com/demo/accept.php”strings.NewReader (" name=可"))   如果犯错!=nil {//处理错误   }      req.Header。集(“内容类型”,“应用程序/x-www-form-urlencoded”)   req.Header。集(“饼干”,“name=安妮”)      职责,犯错:=client.Do(要求)      推迟resp.Body.Close ()      身体,犯错:=ioutil.ReadAll (resp.Body)   如果犯错!=nil {//处理错误   }      fmt.Println (string(身体))   }      

同上面的帖子请求,必须要设定内容类型为应用程序/x-www-form-urlencoded,文章参数才可正常传递。

  

如果要发起头请求可以直接使用http客户机的头上方法,比较简单,这里就不再说明。

  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

golang使用http客户端发起get和post请求示例