欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

golang中的http客户端

发布时间:2025/6/15 编程问答 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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. 200Proto string // e.g. "HTTP/1.0"⋯⋯Header HeaderBody 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 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>

总结

以上是生活随笔为你收集整理的golang中的http客户端的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。