Go net/http 发送常见的 http 请求

使用 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]
", r.Header)

    //获取 post 请求中 form 里边的数据
    fmt.Printf("form content:[%s, %s]
", 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]
", err.Error())
        return
    }
    fmt.Printf("body content:[%s]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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]
", resp.StatusCode)
    fmt.Printf("resp body data:[%s]
", 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~

每天都要遇到更好的自己.
原文地址:https://www.cnblogs.com/kaichenkai/p/11365020.html