C#/.Net crawler request.GetResponse() error: The underlying connection has been closed: Failed to establish a trust relationship for the SSL/TLS secure channel/according to the verification process, the remote certificate is invalid

PS: C#/.Net crawler request.GetResponse() reports an error: the underlying connection has been closed: failed to establish a trust relationship for the SSL/TLS secure channel/according to the verification process, the remote certificate is invalid [the bottom is the complete code]

First, place a picture of the error:

insert image description here
Reason: The certificate of the website should be invalid, and the request I initiated is based on Https, so it is considered an insecure connection by the system. And the explanation through Microsoft's official documentation is as follows:
insert image description here

solution:

1. You need to use the ServicePointManager.SecurityProtoco attribute. The explanation of this attribute is as follows, and you can refer to the official document for details:
insert image description here
The way to use it is to set a value for this attribute before initiating a Request request:

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

The enumerated types are:
insert image description here

2. If there is still a problem after setting this attribute, you must consider whether your client and server are two-way authentication or one-way authentication. By default, most websites use one-way authentication. (Comrades who do not understand one-way authentication or two-way authentication can search related blog posts to understand, and I will not elaborate here). The way to solve this is to use the ServicePointManager.ServerCertificateValidationCallback delegate. This delegation is mainly used for authentication.
insert image description here
insert image description here
Solution: Implement this delegate and force it to return True

 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
    
    
            return true;
        }

The detailed code is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45091053/article/details/128682404