GolangNote

Golang笔记

golang用内置包 net/http 发起 get/post 网络请求示例

Permalink

golang用内置包 net/http 发起 get/post 网络请求示例

golang用内置包 net/http

Go: go http 请求
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
)

func httpGet() {
    resp, err := http.Get("http://www.baidu.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))
}

func httpPost() {
    resp, err := http.Post("http://www.baidu.com",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=baidu"))
    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))
}

func httpPostForm() {
    resp, err := http.PostForm("http://www.baidu.com",
        url.Values{"key": {"Value"}, "id": {"123"}})

    if err != nil {
        // handle error
    }

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

    fmt.Println(string(body))

}

func httpDo() {
    client := &http.Client{}

    req, err := http.NewRequest("POST", "http://www.baidu.com", strings.NewReader("name=baidu"))
    if err != nil {
        // handle error
    }

    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Set("Cookie", "name=baidu")

    resp, err := client.Do(req)

    defer resp.Body.Close()

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

    fmt.Println(string(body))
}

func main() {
    httpGet()
    httpPost()
    httpPostForm()
    httpDo()
}

参考更简单的net/http示例

Related articles

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

golang snappy 示例

snappy 是 google 开源的一种高效的压缩算法,这里是 golang 实现的 snappy 压缩示例...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Write a Comment to "golang用内置包 net/http 发起 get/post 网络请求示例"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 0ms