Go語言中利用http發(fā)起Get和Post請求的方法示例
關于 HTTP 協(xié)議
HTTP(即超文本傳輸協(xié)議)是現(xiàn)代網(wǎng)絡中最常見和常用的協(xié)議之一,設計它的目的是保證客戶機和服務器之間的通信。
HTTP 的工作方式是客戶機與服務器之間的 “請求-應答” 協(xié)議。
客戶端可以是 Web 瀏覽器,服務器端可以是計算機上的某些網(wǎng)絡應用程序。
通常情況下,由瀏覽器向服務器發(fā)起 HTTP 請求,服務器向瀏覽器返回響應。響應包含了請求的狀態(tài)信息以及可能被請求的內(nèi)容。
Go 語言中要請求網(wǎng)頁時,使用net/http包實現(xiàn)。官方已經(jīng)提供了詳細的說明,但是比較粗略,我自己做了一些增加。
一般情況下有以下幾種方法可以請求網(wǎng)頁:
Get, Head, Post, 和 PostForm 發(fā)起 HTTP (或 HTTPS) 請求:
resp, err := http.Get("http://example.com/")
...
//參數(shù) 詳解
//1. 請求的目標 URL
//2. 將要 POST 數(shù)據(jù)的資源類型(MIMEType)
//3. 數(shù)據(jù)的比特流([]byte形式)
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
//參數(shù) 詳解
//1. 請求的目標 URL
//2. 提交的參數(shù)值 可以使用 url.Values 或者 使用 strings.NewReader("key=value&id=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 請求
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 請求(資源提交,比如 圖片上傳)
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))
擴展 Post 表單提交(包括 Header 設置)
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 方式請求
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)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Golan中?new()?、?make()?和簡短聲明符的區(qū)別和使用
Go語言中的new()、make()和簡短聲明符的區(qū)別和使用,new()用于分配內(nèi)存并返回指針,make()用于初始化切片、映射和通道,并返回初始化后的對象,簡短聲明符:=可以簡化變量聲明和初始化過程,感興趣的朋友一起看看吧2025-01-01
Golang并發(fā)繞不開的重要組件之Goroutine詳解
Goroutine、Channel、Context、Sync都是Golang并發(fā)編程中的幾個重要組件,這篇文中主要為大家介紹了Goroutine的相關知識,需要的可以參考一下2023-06-06

