golang的http请求
发布时间:2020-12-16 18:40:22 所属栏目:大数据 来源:网络整理
导读:import("fmt""io/ioutil""net/http""net/url""strings")funchttpGet(){resp,err:=http.Get("http://www.baidu.com")iferr!=nil{//handleerror}deferresp.Body.Close()body,err:=ioutil.ReadAll(resp.Body)iferr!=nil{//handleerror}fmt.Println(string(body)
import( "fmt" "io/ioutil" "net/http" "net/url" "strings" ) funchttpGet(){ resp,err:=http.Get("http://www.baidu.com") iferr!=nil{ //handleerror } deferresp.Body.Close() body,err:=ioutil.ReadAll(resp.Body) iferr!=nil{ //handleerror } fmt.Println(string(body)) } funchttpPost(){ resp,err:=http.Post("http://www.baidu.com","application/x-www-form-urlencoded",strings.NewReader("name=cjb")) iferr!=nil{ fmt.Println(err) } deferresp.Body.Close() body,err:=ioutil.ReadAll(resp.Body) iferr!=nil{ //handleerror } fmt.Println(string(body)) } funchttpPostForm(){ resp,err:=http.PostForm("http://www.baidu.com",url.Values{"key":{"Value"},"id":{"123"}}) iferr!=nil{ //handleerror } deferresp.Body.Close() body,err:=ioutil.ReadAll(resp.Body) iferr!=nil{ //handleerror } fmt.Println(string(body)) } funchttpDo(){ client:=&http.Client{} req,err:=http.NewRequest("POST","http://www.baidu.com",strings.NewReader("name=cjb")) iferr!=nil{ //handleerror } req.Header.Set("Content-Type","application/x-www-form-urlencoded") req.Header.Set("Cookie","name=anny") resp,err:=client.Do(req) deferresp.Body.Close() body,err:=ioutil.ReadAll(resp.Body) iferr!=nil{ //handleerror } fmt.Println(string(body)) } funcmain(){ httpGet() //httpPost() //httpPostForm() //httpDo() } 复杂的请求(要设置http的header的属性等等)用httpDo方法,其它场合用get,post,postform就可以咯 golang中文网net/http包的详解:http://studygolang.com/articles/2680 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |