golang之net/http包简单的get/post请求

1.get请求

  • http.Get
package main

import (
    "fmt"
    "net/http"
)


func main() {
    resp, err := http.Get("https://wwww.baidu.com")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(resp.StatusCode)
}

2.post请求

package main

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

func main() {
    data := url.Values{"app_id":{"238b2213-a8ca-42d8-8eab-1f1db3c50ed6"}, "mobile_tel":{"13794227450"}}
    body := strings.NewReader(data.Encode())
    urlStr := "http://qdgj.myscrm.cn/api/index.php?r=site/login&token=cdkqqf1407307954&from=b2c_h5"
    resp, err := http.Post(urlStr, "application/x-www-form-urlencoded", body)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    bodyC, _ := ioutil.ReadAll(resp.Body)

    var jsonMap map[string]interface{}
    err = json.Unmarshal(bodyC, &jsonMap)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(jsonMap)
}

这里用ioutil.ReadAll(resp.Body)来读取响应
我自己本地的测试接口返回信息如下:

map[app_id:238b2213-a8ca-42d8-8eab-1f1db3c50ed6 mobile_tel:13794227450]

3.细节

首先,直接用http.get或http.post,用的都是DefaultClient来调用get/post:


golang之net/http包简单的get/post请求_第1张图片
image.png

image.png

由此可见,我们可用client来调用,比如:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func main() {
    client := http.Client{
        Timeout: 5* time.Second,
    }
    resp, err := client.Get("http://qdgj.myscrm.cn/api/index.php?r=site/login&token=cdkqqf1407307954&from=b2c_h5")
    if err != nil {
        fmt.Println(err)
        return
    }
    html,_ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(html))
}

上述代码还给client设置了超时时间,我将测试接口休眠6s,得到输出:

Get http://qdgj.myscrm.cn/api/index.php?r=site/login&token=cdkqqf1407307954&from=b2c_h5:
 net/http: request canceled (Client.Timeout exceeded while awaiting headers)

继续看源码,无论get还是post都是用这种方式来创建请求:


golang之net/http包简单的get/post请求_第2张图片
image.png
golang之net/http包简单的get/post请求_第3张图片
image.png

因此,你也可以用这种方式来创建请求,比如:

package main

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

func main() {
    var body io.Reader
    req, err := http.NewRequest("GET", "http://qdgj.myscrm.cn/api/index.php?r=site/login&token=cdkqqf1407307954&from=b2c_h5", body)
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    html,_ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(html))
}

另外,我们再看看request和response有哪些结构体成员:

  • request
type Request struct {
    Method string  //HTTP method (GET, POST, PUT, etc.)
    URL *url.URL // 见下面URL定义
    Proto      string // http协议类型,如 HTTP/1.1,HTTP/2
    ProtoMajor int    // 1
    ProtoMinor int    // 0
    Header Header // 请求头,map[string][]string
    Body io.ReadCloser // http请求body post请求的内容就放在这里
    GetBody func() (io.ReadCloser, error) // 获取body的方法
    ContentLength int64  // 描述HTTP消息实体的传输长度
    TransferEncoding []string  //传输编码, 如chunk
    Close bool 
    Host string // 主机地址,IP或域名
    Form url.Values //URL和参数的map
    PostForm url.Values //POST, PATCH, or PUT body 参数
    MultipartForm *multipart.Form
    Trailer Header
    RemoteAddr string
    RequestURI string //通常就是URL
    TLS *tls.ConnectionState
    Cancel <-chan struct{}
    Response *Response
    ctx context.Context
}

----------------------------------------------
URL定义:
type URL struct {
    Scheme     string
    Opaque     string    // encoded opaque data
    User       *Userinfo // username and password information
    Host       string    // host or host:port
    Path       string    // path (relative paths may omit leading slash)
    RawPath    string    // encoded path hint (see EscapedPath method)
    ForceQuery bool      // append a query ('?') even if RawQuery is empty
    RawQuery   string    // encoded query values, without '?'
    Fragment   string    // fragment for references, without '#'
}
  • response
type Response struct {
    Status     string // e.g. "200 OK"
    StatusCode int    // e.g. 200
    Proto      string // e.g. "HTTP/1.0"
    ProtoMajor int    // e.g. 1
    ProtoMinor int    // e.g. 0
        Header Header //响应头
    Body io.ReadCloser //响应内容
    ContentLength int64 //HTTP消息实体的传输长度
    TransferEncoding []string 
    Close bool
    Uncompressed bool
    Trailer Header
    Request *Request
    TLS *tls.ConnectionState
}

你可能感兴趣的:(golang之net/http包简单的get/post请求)