美文网首页
Go语言http请求

Go语言http请求

作者: 高稚商de菌 | 来源:发表于2018-03-07 00:39 被阅读0次

以下是net/http包中的几种进行http请求的方式:

1. http.Get和http.Post
import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

// http.Get
func httpGet() {
    resp, err := http.Get("http://www.baidu.com")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

func httpPost() {
    resp, err := http.Post("http://www.baidu.com",
                           "application/x-www-form-urlencode",
                           strings.NewReader("name=abc")) // Content-Type post请求必须设置
    if err != nil {
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}
2. http.Client
// http.Client
func httpDo() {
    client := &http.Client{}
    req, err := http.NewRequest("POST", 
                                "http://www.baidu.com", 
                                strings.NewReader("name=abc"))
    if err != nil {
        return
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    resp, err := client.Do(req)
    if err != nil {
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return
    }
    fmt.Println(string(body))
}
简单的http请求直接用http.Get和http.Post。需要操作headers,cookies或使用长连接和连接池,使用http.Client

相关文章

网友评论

      本文标题:Go语言http请求

      本文链接:https://www.haomeiwen.com/subject/yqtdfftx.html