Go語言封裝Http協議GET和POST請求


本文幾乎沒有文字敘述:

 

/*
有關Http協議GET和POST請求的封裝
*/
package net

import (
    "net/http"
    "io"
    "bytes"
    "encoding/json"
    "io/ioutil"
    "time"
)

//發送GET請求
//url:請求地址
//response:請求返回的內容
func Get(url string) (response string) {
    client := http.Client{Timeout: 5 * time.Second}
    resp, error := client.Get(url)
    defer resp.Body.Close()
    if error != nil {
        panic(error)
    }

    var buffer [512]byte
    result := bytes.NewBuffer(nil)
    for {
        n, err := resp.Body.Read(buffer[0:])
        result.Write(buffer[0:n])
        if err != nil && err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
    }

    response = result.String()
    return
}

//發送POST請求
//url:請求地址,data:POST請求提交的數據,contentType:請求體格式,如:application/json
//content:請求放回的內容
func Post(url string, data interface{}, contentType string) (content string) {
    jsonStr, _ := json.Marshal(data)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Add("content-type", contentType)
    if err != nil {
        panic(err)
    }
    defer req.Body.Close()

    client := &http.Client{Timeout: 5 * time.Second}
    resp, error := client.Do(req)
    if error != nil {
        panic(error)
    }
    defer resp.Body.Close()

    result, _ := ioutil.ReadAll(resp.Body)
    content = string(result)
    return
}

 

版權聲明

本文為作者原創,版權歸作者雪飛鴻所有。 轉載必須保留文章的完整性,且在頁面明顯位置處標明原文鏈接

如有問題, 請發送郵件和作者聯系。


免責聲明!

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



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