用于提交,参考链接:http://www.01happy.com/golang-http-client-get-and-post/
Get 方法
func httpGet() { resp, err := http.Get("http://192.168.110.128") if err != nil { // handle error fmt.Println(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error fmt.Println(err) } fmt.Println(string(body)) }
Post 方法
func httpPostForm() { resp, err := http.PostForm("http://192.168.110.128/login", url.Values{"username": {"Tom "}, "password": {"123"}}) if err != nil { fmt.Println(err) // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) // handle error } fmt.Println(string(body)) }
使用client
func httpDo() { client := &http.Client{} req, err := http.NewRequest("POST", "http://192.168.110.128/login", strings.h("username=Tom&password=1234")) if err != nil { fmt.Println(err) // handle error } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") // req.Header.Set("Cookie", "name=anny") resp, err := client.Do(req) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error fmt.Println(err) } fmt.Println(string(body)) }
func NewRequest
NewRequest returns a new Request given a method, URL, and optional body.
If the provided body is also an io.Closer, the returned Request.Body is set to body and will be closed by the Client methods Do, Post, and PostForm, and Transport.RoundTrip.
NewRequest returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler use either ReadRequest or manually update the Request fields. See the Request type’s documentation for the difference between inbound and outbound request fields.
func NewRequest(method, urlStr string, body io.Reader) (*Request, error)