golang中的http客户端

http WEB客户端:

	1. 获取web服务器数据:

		func Get(url string) (resp *Response, err error)

		返回:http应答包,保存成 struct 

		type Response struct {
   			Status     string // e.g. "200 OK"
   			StatusCode int    // e.g.  200
   			Proto      string // e.g. "HTTP/1.0"
  			 ⋯⋯
   			Header Header
   			Body io.ReadCloser
  		 	⋯⋯
		}
	2. defer resp.Body.Close()

	3. for 循环提取 Body 数据:

		n, err := resp.Body.Read(buf) 
		if n == 0 {
			fmt.Println("--Read finish!")
			break
		}
		if err != nil && err != io.EOF {
			fmt.Println("resp.Body.Read err:", err)
			return
		}

使用

func main() {
   //http://这写要写全
   resp, err := http.Get("http://baidu.com")
   if err != nil {
      fmt.Println("http.get err: ", err)
      return
   }

   defer resp.Body.Close()

   fmt.Println("Status = ", resp.Status)
   fmt.Println("StatusCode = ", resp.StatusCode)
   fmt.Println("Header = ", resp.Header)

   //body是个io流需要读取
   buf := make([]byte, 4*1024)
   //创建个字符串来接收
   var tmp string
   for {
      n, err := resp.Body.Read(buf)
      if n == 0 {
         //读取到EOF也不要退出
         fmt.Println("read err: ", err)
         break
      }
      tmp += string(buf[:n])
   }
   fmt.Println("tmp = ", tmp)
}

输出

Status =  200 OK
StatusCode =  200
Header =  map[Accept-Ranges:[bytes] Cache-Control:[max-age=86400] Connection:[Keep-Alive] Content-Length:[81] Content-Type:[text/html] Date:[Wed, 22 May 2019 13:12:23 GMT] Etag:["51-47cf7e6ee8400"] Expires:[Thu, 23 May 2019 13:12:23 GMT] Last-Modified:[Tue, 12 Jan 2010 13:48:00 GMT] Server:[Apache]]
read err:  EOF
tmp =  <html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>

猜你喜欢

转载自blog.csdn.net/ma2595162349/article/details/112911950