GET
请求
get请求可以直接使用
http.Get
方法
简单
func main(){
resp,err := http.Get("https://baidu.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
s,err:=IoUtil.ReadAll(resp.Body)
fmt.Printf(string(s))
}
复杂
func main() {
params := url.Values{}
Url,err := url.Parse("http://baidu.com?fd=fdsf")
if err != nil {
panic(err.Error())
}
params.Set("a","fdfds")
params.Set("id",string("1"))
//如果参数中有中文参数,这个方法会进行URLEncode
Url.RawQuery = params.Encode()
urlPath := Url.String()
resp,err := http.Get(urlPath)
defer resp.Body.Close()
s,err := IoUtil.ReadAll(resp.Body)
fmt.Println(string(s))
}
这个params.set
是不是感觉跟PHP里的http_build_query
,自己感觉哈
POST
请求
使用
http.post
type Server struct {
ServerName string
ServerIp string
}
type ServerSlice struct {
Server []Server
ServersID string
}
func main() {
//post 第三个参数是io.reader interface
//strings.NewReader byte.NewReader bytes.NewBuffer 实现了read 方法
s := ServerSlice{ServersID: "tearm",Server: []Server{{"beijing","127.0.0.1"},{"shanghai","127.0.0.1"}}}
b,_ := json.Marshal(s)
fmt.Println(string(b))
resp,_ := http.Post("http://baidu.com","application/x-www-form-urlencoded",strings.NewReader("heel="+string(b)))
//
defer resp.Body.Close()
//io.Reader
body,_ := IoUtil.ReadAll(resp.Body)
fmt.Println(string(body))
使用
http.PostForm
func httpPostForm() {
// params:=url.Values{}
// params.Set("hello","fdsfs") //这两种都可以
params= url.Values{"key": {"Value"},"id": {"123"}}
resp,_:= http.PostForm("http://baidu.com",body)
defer resp.Body.Close()
body,_:= IoUtil.ReadAll(resp.Body)
fmt.Println(string(body))
}
如果需要设置头参数,cookie之类的数据,就可以使用http.Do
func httpDo() {
client := &http.Client{}
req,err := http.NewRequest("POST","baidu.com",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))
}
同样的http.NewRequest
第三个参数只需要实现io.reader
接口就行
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。