golang 发送get和post示例

本文详细介绍了如何使用Go语言发送GET和POST网络请求,包括直接使用http.Get方法进行简单的GET请求,以及通过设置URL参数、使用JSON数据进行复杂的POST请求。同时,还讲解了如何设置请求头和cookie等高级功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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接口就行

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值