This is a creation in Article, where the information may have evolved or changed.
Golang to request a remote Web page, it can be implemented using the method provided by the client in the Net/http package. See the official website There are some examples, there are not too comprehensive examples, so I tidied up a bit.
GET request
Get requests can be directly HTTP. The Get method is very simple.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
funchttpGet() { resp, err := http.Get("http://www.01happy.com/demo/accept.php?id=1") iferr != nil { // handle error } deferresp.Body.Close() body, err := ioutil.ReadAll(resp.Body) iferr != nil { // handle error } fmt.Println(string(body)) } |
POST request
One is to use HTTP. Post mode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
funchttpPost() { resp, err := http.Post("http://www.01happy.com/demo/accept.php", "application/x-www-form-urlencoded", strings.NewReader("name=cjb")) iferr != nil { fmt.Println(err) } deferresp.Body.Close() body, err := ioutil.ReadAll(resp.Body) iferr != nil { // handle error } fmt.Println(string(body)) } |
Tips: Using this method, the second parameter is set to "application/x-www-form-urlencoded", otherwise the post parameter cannot be passed.
One is to use HTTP. Postform method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
funchttpPostForm() { resp, err := http.PostForm("http://www.01happy.com/demo/accept.php", url.Values{"key": {"Value"}, "id": {"123"}}) iferr != nil { // handle error } deferresp.Body.Close() body, err := ioutil.ReadAll(resp.Body) iferr != nil { // handle error } fmt.Println(string(body)) } |
A complex request
Sometimes you need to set the header parameters, cookies and other data at the time of the request, you can use HTTP. Do method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 |
funchttpDo() { client := &http.Client{} req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader("name=cjb")) iferr != nil { // handle error } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Cookie", "name=anny") resp, err := client.Do(req) deferresp.Body.Close() body, err := ioutil.ReadAll(resp.Body) iferr != nil { // handle error } fmt.Println(string(body)) } |
With the above POST request, you must set Content-type as the Application/x-www-form-urlencoded,post parameter to pass normally.
If you want to initiate a head request can be directly using the HTTP client head method, relatively simple, here is no longer explained.