1. 程式人生 > >Go語言中利用http發起Get和Post請求的方法示例

Go語言中利用http發起Get和Post請求的方法示例

關於 HTTP 協議

HTTP(即超文字傳輸協議)是現代網路中最常見和常用的協議之一,設計它的目的是保證客戶機和伺服器之間的通訊。

HTTP 的工作方式是客戶機與伺服器之間的 “請求-應答” 協議。

客戶端可以是 Web 瀏覽器,伺服器端可以是計算機上的某些網路應用程式。

通常情況下,由瀏覽器向伺服器發起 HTTP 請求,伺服器向瀏覽器返回響應。響應包含了請求的狀態資訊以及可能被請求的內容。

Go 語言中要請求網頁時,使用net/http包實現。官方已經提供了詳細的說明,但是比較粗略,我自己做了一些增加。

一般情況下有以下幾種方法可以請求網頁:

Get, Head, Post, 和 PostForm 發起 HTTP (或 HTTPS) 請求:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

resp, err := http.Get("http://example.com/")

...

  

//引數 詳解

//1. 請求的目標 URL

//2. 將要 POST 資料的資源型別(MIMEType)

//3. 資料的位元流([]byte形式)

resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)

...

  

//引數 詳解

//1. 請求的目標 URL

//2. 提交的引數值 可以使用 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 請求

?

1

2

3

4

5

6

7

8

9

10

11

12

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 請求(資源提交,比如 圖片上傳)

?

1

2

3

4

5

6

7

8

9

10

11

12

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 表單提交

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

postValue := url.Values{

"email": {"[email protected]"},

"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 設定)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

postValue := url.Values{

"email": {"[email protected]"},

"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

 

轉自https://www.jb51.net/article/128683.htm