傳入請求地址url,請求參數params
func PostReq(url string, params string) (string, error) {
// 1. 創建http客戶端實例
client := &http.Client{}
// 2. 創建請求實例
req, err := http.NewRequest("POST", url, strings.NewReader(params))
if err != nil {
panic(err)
}
// 3. 設置請求頭,可以設置多個
req.Header.Set("Host", " ")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// 4. 發送請求
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// 5. 一次性讀取請求到的數據
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return string(body)
}