如何使用HTTP GET在C#中使用SSL的要求吗? (违反协议) [英] How to use HTTP GET request in C# with SSL? (protocol violation)
问题描述
目前我正在试图让从在C#中使用SSL服务器的响应。我的代码在Java中做到这一点,但看起来他们并没有转化为1:1。
I am currently trying to get a response from a server that is using SSL in C#. I have the code to do this in Java, but it looks like they do not translate 1:1.
我有一些代码,我发现,对于普通页面的作品,而不是一个我需要(的也许是因为SSL的事)。下面是代码:
I do have some code that I found that works for regular pages, but not for the one I need (maybe because of the SSL thing). Here is the code:
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响应=(HttpWebResponse)request.GetResponse();行。
任何想法?谢谢你们。
UPDATE: Sorry I seem to have forgotten what the error is. I'm getting a protocol violation exception at the "HttpWebResponse response = (HttpWebResponse)request.GetResponse(); " line. Any ideas? Thanks guys.
推荐答案
HTTP会话。
您可以使用RemoteCertificateValidationCallback委托验证SSL证书,如下所示:
You could use the RemoteCertificateValidationCallback delegate for validating the SSL certificate as follows:
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;
}
这篇关于如何使用HTTP GET在C#中使用SSL的要求吗? (违反协议)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!