Go语言-http请求

摘要

Go语言封装Http协议GET和POST请求

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
13
14
func httpGet() {
resp, err := http.Get("http://c.isme.pub")
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
// url参数
func httpPost() {
resp, err := http.Post("http://c.isme.pub",
"application/x-www-form-urlencoded",
strings.NewReader("name=cjb"))
if err != nil {
fmt.Println(err)
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}

表单提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func httpPostForm() {
postValue := url.Values{
"email": {"xx@xx.com"},
"password": {"123456"},
}
resp, err := http.PostForm("http://c.isme.pub", 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))
}

图片上传

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 表单提交(包括 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
func httpDo() {
postValue := url.Values{
"email": {"xx@xx.com"},
"password": {"123456"},
}
postString := postValue.Encode()

req, err := http.NewRequest("POST", "http://c.isme.pub", strings.NewReader(postString))
if err != nil {
// handle error
}

// 这种方法是参数直接在header里面的
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("x-requested-with", "XMLHttpRequest")
req.Header.Set("Cookie", "name=anny")

client := &http.Client{}
resp, err := client.Do(req)

defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}

fmt.Println(string(body))
}

示例

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
有关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,这种方式json是在body中传递
//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
}

url

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

package main
import (
"fmt"
"net/url"
"net/http"
"io/ioutil"
"log"
)
func main() {
u, _ := url.Parse("http://localhost:9001/x")
q := u.Query()
q.Set("username", "user")
q.Set("password", "passwd")
u.RawQuery = q.Encode()
res, err := http.Get(u.String());
if err != nil {
log.Fatal(err) return
}
result, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err) return
}
fmt.Printf("%s", result)
}