golang使用http client发起get和post请求示例

时间:2025-02-28 18:49:14

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


get请求

get请求可以直接方法,非常简单。



func httpGet() {

    resp, err := ("http:///demo/?id=1")

    if err != nil {

        // handle error

    }

 

    defer ()

    body, err := ()

    if err != nil {

        // handle error

    }

 

    (string(body))

}

post请求

一种是使用方式


func httpPost() {

    resp, err := ("http:///demo/",

        "application/x-www-form-urlencoded",

        ("name=cjb"))

    if err != nil {

        (err)

    }

 

    defer ()

    body, err := ()

    if err != nil {

        // handle error

    }

 

    (string(body))

}

Tips:使用这个方法的话,第二个参数要设置成”application/x-www-form-urlencoded”,否则post参数无法传递。


一种是使用方法


func httpPostForm() {

    resp, err := ("http:///demo/",

        {"key": {"Value"}, "id": {"123"}})

 

    if err != nil {

        // handle error

    }

 

    defer ()

    body, err := ()

    if err != nil {

        // handle error

    }

 

    (string(body))

 

}

复杂的请求

有时需要在请求的时候设置头参数、cookie之类的数据,就可以使用方法。



func httpDo() {

    client := &{}

 

    req, err := ("POST", "http:///demo/", ("name=cjb"))

    if err != nil {

        // handle error

    }

 

    ("Content-Type", "application/x-www-form-urlencoded")

    ("Cookie", "name=anny")

 

    resp, err := (req)

 

    defer ()

 

    body, err := ()

    if err != nil {

        // handle error

    }

 

    (string(body))

}

同上面的post请求,必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递。


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


完整代码示例文件下载:golang_http_client发起get和post代码示例


本文来自:博客园


感谢作者:cnsanshao


查看原文:golang使用http client发起get和post请求示例