• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Gonet/http发送常见的http请求

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

使用 golang 中的 net/http 包来发送和接收 http 请求

开启 web server

先实现一个简单的 http server,用来接收请求

package main
import (
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
)

func IndexHandler(w http.ResponseWriter, r *http.Request){
    //打印请求主机地址
    fmt.Println(r.Host)
    //打印请求头信息
    fmt.Printf("header content:[%v]\n", r.Header)

    //获取 post 请求中 form 里边的数据
    fmt.Printf("form content:[%s, %s]\n", r.PostFormValue("username"), r.PostFormValue("passwd"))

    //读取请求体信息
    bodyContent, err := ioutil.ReadAll(r.Body)
    if err != nil && err != io.EOF {
        fmt.Printf("read body content failed, err:[%s]\n", err.Error())
        return
    }
    fmt.Printf("body content:[%s]\n", string(bodyContent))

    //返回响应内容
    fmt.Fprintf(w, "hello world ~")
}

func main (){
    http.HandleFunc("/index", IndexHandler)
    http.ListenAndServe("10.10.19.200:8000", nil)
}

 

发送 GET 请求

最基本的GET请求

package main
import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func httpGet(url string) (err error) {
    resp, err := http.Get(url)
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index"
    httpGet(url)
}

 

带参数的 GET 请求

1)在 url 后面携带参数

package main
import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func httpGet(url string) (err error) {
    resp, err := http.Get(url)
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index?query=googlesearch"
    httpGet(url)
}

 

2)如果想要把一些参数做成变量,然后放到 url 中,可以参考下面的方式

package main
import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

func httpGet(requestUrl string) (err error) {
    Url, err := url.Parse(requestUrl)
    if err != nil {
        fmt.Printf("requestUrl parse failed, err:[%s]", err.Error())
        return
    }

    params := url.Values{}
    params.Set("query","googlesearch")
    params.Set("content","golang")
    Url.RawQuery = params.Encode()

    requestUrl = Url.String()
    fmt.Printf("requestUrl:[%s]\n", requestUrl)

    resp, err := http.Get(requestUrl)
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index"
    httpGet(url)
}

运行结果:

requestUrl:[http://10.10.19.200:8000/index?content=golang&query=googlesearch]
resp status code:[200]
resp body data:[hello world ~]

 

GET 请求添加请求头

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func httpGet(requestUrl string) (err error) {
    client := &http.Client{}
    requestGet, _:= http.NewRequest("GET", requestUrl, nil)

    requestGet.Header.Add("query", "googlesearch")
    requestGet.Header.Add("content", "golang")

    resp, err := client.Do(requestGet)
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index"
    httpGet(url)
}

从 http server 端可以看到设置的请求头数据:

type:[http.Header], header content:[map[Accept-Encoding:[gzip] Content:[golang] Query:[googlesearch] User-Agent:[Go-http-client/1.1]]]

 

发送 POST 请求

发送 form 表单格式的 post 请求

package main
import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

func httpPost(requestUrl string) (err error) {
    data := url.Values{}
    data.Add("username", "seemmo")
    data.Add("passwd", "da123qwe")

    resp, err := http.PostForm(requestUrl, data)
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index"
    httpPost(url)
}

 

发送 json 格式的 post 请求

1)使用 http.Client

下面的请求中没有携带请求头 Content-Type

package main
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func httpPost(requestUrl string) (err error) {
    client := &http.Client{}

    data := make(map[string]interface{})
    data["name"] = "seemmo"
    data["passwd"] = "da123qwe"
    jsonData, _ := json.Marshal(data)

    requestPost, err := http.NewRequest("POST", requestUrl, bytes.NewReader(jsonData))
    resp, err := client.Do(requestPost)
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index"
    httpPost(url)
}

 

2)使用 http.Post

package main
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func httpPost(requestUrl string) (err error) {
    data := make(map[string]interface{})
    data["name"] = "seemmo"
    data["passwd"] = "da123qwe"
    jsonData, _ := json.Marshal(data)

    resp, err := http.Post(requestUrl, "application/json", bytes.NewReader(jsonData))
    if err != nil {
        fmt.Printf("get request failed, err:[%s]", err.Error())
        return
    }
    defer resp.Body.Close()

    bodyContent, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
    fmt.Printf("resp body data:[%s]\n", string(bodyContent))
    return
}

func main() {
    var url = "http://10.10.19.200:8000/index"
    httpPost(url)
}

 

 

参考链接:https://www.cnblogs.com/zhaof/p/11346412.html

 

 

ending~

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go语言调用append之后是否重新分配内存?发布时间:2022-07-10
下一篇:
go defer详解发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap