头图来源:Sakura-日向あずり-pixiv


这两天在写个爬虫,要爬的网站没有使用HTTPS被浏览器提示为不安全(废话),我依然还是按照默认配置开了个http.Client,然后就遇到了如下错误:

Get "https://*******": x509: certificate has expired or is not yet valid:

fine,提示没有证书或证书过期了(网站压根就没有证书艹)。当我把请求url中的https改为http后依然遇到了上面的错误,奇怪我明明请求的是http,为什么一发送请求就又变成了https?
于是乎去查了下Go的net/http包,Client结构体中有个Transport属性(RoundTripper类型),主要用于配置http连接池的一些属性,其中RoundTripper是个接口,Transport结构体实现了接口中的方法,Transport中的TLSClientConfig属性有个InsecureSkipVerify选项,默认为false(即默认请求都是走https),我们把它设定为true就行了。

    /*
        请求非安全http
    */
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }

    client := http.Client{
        Transport: tr,
    }
Last modification:September 4th, 2023 at 10:11 pm
If you think my article is useful to you, please feel free to appreciate