第十章_网络编程,36_网络编程_http客户端

实现HTTP客户端访问网址,打印响应数据

源代码

package main

import (
	"fmt"
	"net/http"
)

func main() {
    
    
	// resp, err1 := http.Get("http://www.baidu.com")//数据量太大
	resp, err1 := http.Get("http://127.0.0.1:8000/go.html")
	if err1 != nil {
    
    
		fmt.Println("http.Get err1 = ", err1)
		return
	}
	defer resp.Body.Close()

	fmt.Println("resp.Status = ", resp.Status)         //状态
	fmt.Println("resp.StatusCode = ", resp.StatusCode) //状态码
	fmt.Println("resp.Header = ", resp.Header)         //响应头部
	fmt.Println("resp.Body = ", resp.Body)             //响应包体,指针类型

	buf := make([]byte, 4*1024)
	var str string
	for {
    
    
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
    
    
			fmt.Println("resp.Body.Read err2 = ", err2)
			break
		}
		str += string(buf[:n])
	}
	fmt.Println("str = ", str)
}

打印输出

resp.Status =  200 OK
resp.StatusCode =  200
resp.Header =  map[Content-Length:[8] Content-Type:[text/plain; charset=utf-8] Date:[Thu, 04 Mar 2021 04:37:07 GMT]]
resp.Body =  &{
    
    0xc00018c000 {
    
    0 0} false <nil> 0x5ca560 0x5ca4e0}
resp.Body.Read err2 =  EOF
str =  hello go

猜你喜欢

转载自blog.csdn.net/weixin_40355471/article/details/115288543