Go语言http请求

以下是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
    原文作者:高稚商de菌
    原文地址: https://www.jianshu.com/p/9aea4498885a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞