go http.Get(), http.Head() io/ioutil ioutil.ReadAll(res.Body) 和 http.Get()

http.Get() https://golang.org/pkg/net/http/#Client

package main

import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
	res, err := http.Get("https://www.baidu.com")
	if err != nil {
		fmt.Println("get err:", err)
		return
	}
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("get data err:", err)
		return
	}

	fmt.Println(string(data))
}



http.Head()

package main

import (
	"fmt"
	"net/http"
)

var url = []string {
	"http://www.baidu.com",
	"http://google.com",
	"http://taobao.com",
}
func main(){
	for _,v := range url{
		resp, err := http.Head(v)
		if err != nil {
			fmt.Printf("head %s failed, err:%v \n", v, err)
			continue
			}
		fmt.Printf("head succ, status:%v", resp.Status)
	}
}

http.Head 升级,设置超时时间 Transport 是http网络传输传输底层的的一些东西,此处设置超时时间

package main

import (
	"fmt"
	"net"
	"net/http"
	"time"
)

var url = []string {
	"http://www.baidu.com",
	"http://google.com",
	"http://taobao.com",
}

//Transport  是http网络传输传输底层的的一些东西,此处设置超时时间
func main(){
	for _, v := range url{
	c := http.Client{  //
		Transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error){
				timeout := time.Second * 2
				return net.DialTimeout(network, addr, timeout)
			},
		},
	}
	resp, err := c.Head(v)
	if err != nil {
		fmt.Printf("head %s failed, err:%v \n", v, err)
		continue
		}
	fmt.Printf("head succ, status:%v", resp.Status)
	}
}

http常用状态码

http.StatusContinue=100
http.StatusOK=200
http.StatusFound =302
http.StatusBadRequest=400
http.StatusUnauthorized =401
http.StatusForbidden =403
http.StatusNotFound = 404
http.StatusInternalServerError = 500
posted @ 2022-03-20 23:29  ty1539  阅读(73)  评论(0编辑  收藏  举报