7.3 http客户端(GET、POST、POSTFORM、DO)

示例:

1、实现Get请求方法

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. func main() {
  8. requestUrl := "http://www.baidu.com"
  9. response, err := http.Get(requestUrl)
  10. if err != nil {
  11. fmt.Println(err)
  12. }
  13. defer response.Body.Close()
  14. body, _ := ioutil.ReadAll(response.Body)
  15. fmt.Println(string(body))
  16. }

2、实现post请求方法

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. )
  9. func main() {
  10. requestUrl := "http://www.baidu.com/"
  11. postValue := url.Values{
  12. "username": {"aa"},
  13. "address": {"bb"},
  14. "subject": {"cc"},
  15. "form": {"dd"},
  16. }
  17. //request, err := http.PostForm(requestUrl, postValue)
  18. body := bytes.NewBufferString(postValue.Encode())
  19. request, err := http.Post(requestUrl, "text/html", body)
  20. if err != nil {
  21. fmt.Println(err)
  22. }
  23. defer request.Body.Close()
  24. fmt.Println(request.StatusCode)
  25. if request.StatusCode == 200 {
  26. rb, err := ioutil.ReadAll(request.Body)
  27. if err != nil {
  28. fmt.Println(rb)
  29. }
  30. fmt.Println(string(rb))
  31. }
  32. }

3、 实现PostForm请求方法

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/url"
  6. "net/http"
  7. )
  8. func main() {
  9. requestUrl := "http://www.baidu.com/"
  10. postValue := url.Values{
  11. "username": {"aa"},
  12. "address": {"bb"},
  13. "subject": {"cc"},
  14. "form": {"dd"},
  15. }
  16. request, err := http.PostForm(requestUrl, postValue)
  17. if err != nil {
  18. fmt.Println(err)
  19. }
  20. defer request.Body.Close()
  21. fmt.Println(request.StatusCode)
  22. if request.StatusCode == 200 {
  23. rb, err := ioutil.ReadAll(request.Body)
  24. if err != nil {
  25. fmt.Println(rb)
  26. }
  27. fmt.Println(string(rb))
  28. }
  29. }

4、http.Do

使用http.Do方法可以在请求的时候设置头参数、cookie之类的数据。

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. func main() {
  8. client := &http.Client{}
  9. request, err := http.NewRequest("GET", "http://www.baidu.com", nil)
  10. if err != nil {
  11. fmt.Println(err)
  12. }
  13. cookie := &http.Cookie{Name: "JERRY", Value: "dkfsf"}
  14. request.AddCookie(cookie) //向request中添加cookie
  15. //设置request的header
  16. request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
  17. response, err := client.Do(request)
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. defer response.Body.Close()
  23. fmt.Println(response.StatusCode)
  24. if response.StatusCode == 200 {
  25. r, err := ioutil.ReadAll(response.Body)
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. fmt.Println(string(r))
  30. }
  31. }

links