HTTP - cruisechang/wiki-golang GitHub Wiki

#Client

Request Methods

http.Get()

 resp, err := http.Get("http://www.hhh.com/demo/accept.php?id=1")
    if err != nil {
        // handle error
    }
  defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
 
    fmt.Println(string(body))

http.Post()

第二個參數BodyType要設成"application/x-www-form-urlencoded",否則錯誤

BodyType parameters must set to Content-Type header is set to application/x-www-form-urlencoded.

 resp, err := http.Post("http://www.hhh.com/demo/accept.php",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=cjb"))
    if err != nil {
        fmt.Println(err)
    }

http.PostForm()

http.PostForm 內建Content-Type header = application/x-www-form-urlencoded.所以不需要設定

resp, err := http.PostForm("http://www.hhh.com/demo/accept.php",
        url.Values{"key": {"Value"}, "id": {"12345"}})

New Client.NewRequest And Do

需要設定header = application/x-www-form-urlencoded.

client := &http.Client{
	CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")
// ...

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...