golang USES http client to initiate examples of get and post requests

  • 2020-10-23 20:08:04
  • OfStack

To request remote web pages from golang, you can use the methods provided by client in the net/http package. There are some examples on the official website, but there are not too comprehensive examples, so I sorted out the following ones by myself:

get request


func httpGet() {
  resp, err :=  http.Get("http://www.01happy.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))
}

post request

http Post way


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

  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    // handle error
  }

  fmt.Println(string(body))
}

Tips: To use this method, the second parameter should be set to "application/ x-ES25en-ES26en-ES27en", otherwise the post parameter cannot be passed.

http PostForm method


func httpPostForm() {
  resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
    url.Values{"key": {"Value"}, "id": {"123"}})

  if err != nil {
    // handle error
  }

  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    // handle error
  }

  fmt.Println(string(body))

}

Complex request

Sometimes you need to set header parameters, cookie, and so on at request, and you can use the http.Do method.


func httpDo() {
  client := &http.Client{}

  req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader("name=cjb"))
  if err != nil {
    // 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(string(body))
}

As for post request above, Content-ES48en must be set as application/ ES50en-ES51en-ES52en-ES53en before the post parameter can be passed normally.

If you want to make an head request, you can simply use the head method of http client, which is simpler and will not be explained here.


Related articles: