golang中的http客户端
生活随笔
收集整理的這篇文章主要介紹了
golang中的http客户端
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
http WEB客戶端:
1. 獲取web服務(wù)器數(shù)據(jù):func Get(url string) (resp *Response, err error)返回:http應(yīng)答包,保存成 struct type Response struct {Status string // e.g. "200 OK"StatusCode int // e.g. 200Proto string // e.g. "HTTP/1.0"??Header HeaderBody io.ReadCloser??}2. defer resp.Body.Close()3. for 循環(huán)提取 Body 數(shù)據(jù):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)//創(chuàng)建個字符串來接收var tmp stringfor {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>總結(jié)
以上是生活随笔為你收集整理的golang中的http客户端的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang中的http服务器
- 下一篇: golang中的爬虫