如何在C#中使用SSL的HTTP GET请求? (违反协议)

时间:2009-04-02 03:47:13

标签: c# http ssl

我目前正在尝试从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();”行中遇到了协议违规异常。 有任何想法吗?谢谢你们。

3 个答案:

答案 0 :(得分:14)

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; 
}

答案 1 :(得分:2)

只是一个想法,但你用最后的“/”尝试过吗?此外 - 您可能会发现这种方法更容易:

string s;
using(WebClient client = new WebClient()) {
    client.UseDefaultCredentials = true;
    s = client.DownloadString("https://" + sslServerHost + ":"
       + sslServerPort + "/");
}

答案 2 :(得分:1)

以下是我成功用于测试SSL连接的一些测试代码......

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.dscoduc.com");
//request.Method = "HEAD";
//request.AllowAutoRedirect = false;
request.Credentials = CredentialCache.DefaultCredentials;

// Ignore Certificate validation failures (aka untrusted certificate + certificate chains)
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); 

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string responseFromServer = reader.ReadToEnd();