golang發送POST請求(net/http)


傳入請求地址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)
  }


免責聲明!

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



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