我目前正在尝试从在C#中使用SSL的服务器获得响应.我有在Java中执行此操作的代码,但看起来它们不会以1:1进行翻译.
我确实有一些代码,我发现它适用于常规页面,但不适用于我需要的代码(可能是因为SSL的事情).这是代码:
WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort); request.Proxy = null; request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd();
更新:对不起,我似乎忘记了错误是什么.我在"HttpWebResponse response =(HttpWebResponse)request.GetResponse();"行中遇到了协议违规异常.有任何想法吗?多谢你们.
SSL上的HTTP会话使用正确颁发的证书进行验证.
您可以使用RemoteCertificateValidationCallback委托来验证SSL证书,如下所示:
public static void ConnectSSL() { WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort); request.Proxy = null; request.Credentials = CredentialCache.DefaultCredentials; //allows for validation of SSL certificates ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); } //for testing purpose only, accept any dodgy certificate... public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }