Go 发送 HTTP 请求

Go HTTP About 1,496 words

Get

内置了http.Get函数,可以直接发起Get请求。

v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
v.Add("friend", "Sarah")
v.Add("friend", "张三")

fmt.Println(v.Get("name"))
fmt.Println(v.Get("friend"))
fmt.Println(v["friend"])

encode := v.Encode() // v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"

res, err := http.Get("https://www.baidu.com?" + encode)
if err != nil {
    log.Fatal(err)
}
defer res.Body.Close()

body, _ := io.ReadAll(res.Body)
log.Println(string(body))

Post

内置了http.Post函数,可以直接发起Post请求。

定义Content-Type,并传入请求体。

v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
v.Add("friend", "Sarah")
v.Add("friend", "张三")

encode := v.Encode()

response, err := http.Post("http://www.baidu.com", "application/json", strings.NewReader(encode))
if err != nil {
    log.Fatal(err)
}
defer response.Body.Close()

println(response.StatusCode)

自定义请求

对于其他请求:PUTDELETEPATCH等,可以使用http.NewRequest函数。

payload := map[string]string{"name": "New Name"}

// encode payload to JSON
jsonPayload, err := json.Marshal(payload)
if err != nil {
    panic(err)
}

request, err := http.NewRequest(http.MethodPut, "http://url.com", bytes.NewBuffer(jsonPayload))
if err != nil {
    log.Fatal(err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("head1", "value1")

resp, err := http.DefaultClient.Do(request)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

body, _ := io.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
Views: 632 · Posted: 2023-09-21

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh