關(guān)于 HTTP 協(xié)議
HTTP(即超文本傳輸協(xié)議)是現(xiàn)代網(wǎng)絡(luò)中最常見和常用的協(xié)議之一,設(shè)計(jì)它的目的是保證客戶機(jī)和服務(wù)器之間的通信。
HTTP 的工作方式是客戶機(jī)與服務(wù)器之間的 “請(qǐng)求-應(yīng)答” 協(xié)議。
客戶端可以是 Web 瀏覽器,服務(wù)器端可以是計(jì)算機(jī)上的某些網(wǎng)絡(luò)應(yīng)用程序。
通常情況下,由瀏覽器向服務(wù)器發(fā)起 HTTP 請(qǐng)求,服務(wù)器向?yàn)g覽器返回響應(yīng)。響應(yīng)包含了請(qǐng)求的狀態(tài)信息以及可能被請(qǐng)求的內(nèi)容。
Go 語言中要請(qǐng)求網(wǎng)頁時(shí),使用net/http包實(shí)現(xiàn)。官方已經(jīng)提供了詳細(xì)的說明,但是比較粗略,我自己做了一些增加。
一般情況下有以下幾種方法可以請(qǐng)求網(wǎng)頁:
Get, Head, Post, 和 PostForm 發(fā)起 HTTP (或 HTTPS) 請(qǐng)求:
resp, err := http.Get("http://example.com/") ... //參數(shù) 詳解 //1. 請(qǐng)求的目標(biāo) URL //2. 將要 POST 數(shù)據(jù)的資源類型(MIMEType) //3. 數(shù)據(jù)的比特流([]byte形式) resp, err := http.Post("http://example.com/upload", "image/jpeg", buf) ... //參數(shù) 詳解 //1. 請(qǐng)求的目標(biāo) URL //2. 提交的參數(shù)值 可以使用 url.Values 或者 使用 strings.NewReader("key=valueid=123") // 注意,也可以 url.Value 和 strings.NewReader 并用 strings.NewReader(url.Values{}.Encode()) resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
下面是分析:
Get 請(qǐng)求
resp, err := http.Get("http://example.com/") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
Post 請(qǐng)求(資源提交,比如 圖片上傳)
resp, err := http.Post("http://example.com/upload", "image/jpeg", buf) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
Post 表單提交
postValue := url.Values{ "email": {"xx@xx.com"}, "password": {"123456"}, } resp, err := http.PostForm("http://example.com/login", postValue) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
擴(kuò)展 Post 表單提交(包括 Header 設(shè)置)
postValue := url.Values{ "email": {"xx@xx.com"}, "password": {"123456"}, } postString := postValue.Encode() req, err := http.NewRequest("POST","http://example.com/login_ajax", strings.NewReader(postString)) if err != nil { // handle error } // 表單方式(必須) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") //AJAX 方式請(qǐng)求 req.Header.Add("x-requested-with", "XMLHttpRequest") client := http.Client{} resp, err := client.Do(req) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
比較 GET 和 POST
下面的表格比較了兩種 HTTP 方法:GET 和 POST
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
標(biāo)簽:瀘州 泰安 阿壩 東營 滄州 晉中 駐馬店 昭通
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Go語言中利用http發(fā)起Get和Post請(qǐng)求的方法示例》,本文關(guān)鍵詞 語,言中,利用,http,發(fā)起,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。