杀手阿一 下载,遵义汽车站,孤月行txt
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执行go get私有库提示"410 Gone" 的问题及解决办法
golang实现微信小程序商城后台系统(moshopserver)
网友评论