Go http client 发送 get post 请求


引入包

import (
    "net/http"
)

发送 get 请求

res, _ := http.Get(getURL)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))

发送 post 请求

// 将 map 转换成 json jinxingfasong
requestJSON, _ := json.Marshal(requestMap)
req, _ := http.NewRequest("POST", postURL, strings.NewReader(string(requestJSON)))
// 设置请求头
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
    fmt.Println(err)
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
分享:

评论