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]\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~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM