如何使用WebRequest连接SSL网站

寻找了很多地方,在一个国外的网站找到如下答案,分享给大家:

http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.aspnet/2006-03/msg02317.html     

在新窗口中打开此链接

  

// NET 1.0 /1.1 version:
// ======================

using  System.Net;
using  System.Security.Cryptography.X509Certificates;

///
/// 使用WebRequest连接之前调用此方法就可以了.
///

private   void  MethodToAccessSSL()
{
// 
ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

//  WebRequest myRequest = WebRequest.Create(url); 
}




internal   class  AcceptAllCertificatePolicy : ICertificatePolicy
{
  
public AcceptAllCertificatePolicy() { }
  
public bool CheckValidationResult(ServicePoint sPoint,
  X509Certificate cert, WebRequest wRequest,
int certProb)
  
{
    
return true;
  }

}



// NET 2.0 Version
//==============


using  System.Net;
using  System.Security.Cryptography.X509Certificates;
using  System.Net.Security;

///
/// 使用WebRequest连接之前调用此方法就可以了.
///

private   void  MethodToAccessSSL()
{
  
// 
  ServicePointManager.ServerCertificateValidationCallback =
       
new RemoteCertificateValidationCallback(ValidateServerCertificate);
  
//WebRequest myRequest = WebRequest.Create(url); 
}



//  The following method is invoked by the RemoteCertificateValidationDelegate.
public   static   bool  ValidateServerCertificate(
    
object  sender,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
  
{
    
if (sslPolicyErrors == SslPolicyErrors.None)
      
return true;

    Console.WriteLine(
"Certificate error: {0}", sslPolicyErrors);

    
// Do not allow this client to communicate with unauthenticated servers.
    return false;
}

你可能感兴趣的:(request)