当前位置: 首页 > 知识库问答 >
问题:

如何用HttpWebRequest实现SSL?

童铭晨
2023-03-14

如何将SSL证书引入HttpWebRequest类?

class MyHttpWebRequest : IDisposable
{
    private static int Count = 0;
    private HttpWebRequest request;
    private Stream dataStream;
    private string Status { get; set; }

    private string userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
    private string accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
    private string acceptLanguage = "Accept-Language: en-US,en;q=0.9";
    private string acceptEncoding = "Accept-Encoding: gzip, deflate, br";
    private string host;
    private X509Certificate2 clientCertificates;
    private String referer { get; set; } = "";
    private CookieCollection cookieCollection { get; set; } = null;

    public MyHttpWebRequest()
    {
        Count++;
        clientCertificates = new X509Certificate2(@"mahan.cer");
        //clientCertificates = X509Certificate.CreateFromCertFile(@"mahan.cer");//(@"LocalAuthority.crt");
        //ServicePointManager.Expect100Continue = true;
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        //ServicePointManager.Expect100Continue = false;
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        //WebRequestHandler handler = new WebRequestHandler();
        //X509Certificate2 certificate = GetMyX509Certificate();
        //handler.ClientCertificates.Add(certificate);
        //HttpClient client = new HttpClient(handler);
    }
    public MyHttpWebRequest(string host) : this()
    {
        this.host = host;
    }
    ~MyHttpWebRequest()
    {
        Count--;
    }
    public string GetResponse()
    {
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (cookieCollection == null) cookieCollection = new CookieCollection();
            cookieCollection.Add(response.Cookies);
            this.Status = response.StatusDescription;

            dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);

            string responseFromServer = reader.ReadToEnd();

            // Clean up the streams.
            reader.Close();
            //dataStream.Close();
            response.Close();

            //clientCertificates = new X509Certificate2(request.ServicePoint.Certificate);

            this.Status = "Successful";
            return responseFromServer;
        }
        catch (Exception ex)
        {
            this.Status = ex.Message;
            return ex.ToString();
        }

    }
    public string SetRequest(string url)
    {
        try
        {
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.UserAgent = userAgent;
            request.Accept = accept;
            request.Headers.Add(acceptLanguage);
            request.Headers.Add(acceptEncoding);
            request.KeepAlive = true;
            request.CookieContainer = new CookieContainer();
            if (cookieCollection != null)
                request.CookieContainer.Add(cookieCollection);
            request.ProtocolVersion = HttpVersion.Version11;
            request.AllowAutoRedirect = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = referer;
            referer = url;
            request.Host = host;
            //request.ClientCertificates.Clear();
            request.ClientCertificates.Add(clientCertificates);
            request.PreAuthenticate = true;

            this.Status = "Successful";
        }
        catch (Exception ex)
        {
            this.Status = ex.ToString();
        }
        return this.ToString();
    }
    public string SetRequest(string url, string method)
    {
        try
        {
            request = (HttpWebRequest)WebRequest.Create(url);
            if (method.Equals("GET") || method.Equals("POST"))
            {
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
            request.UserAgent = userAgent;
            request.Accept = accept;
            request.Headers.Add(acceptLanguage);
            request.Headers.Add(acceptEncoding);
            request.KeepAlive = true;
            request.CookieContainer = new CookieContainer();
            if (cookieCollection != null)
                request.CookieContainer.Add(cookieCollection);
            request.ProtocolVersion = HttpVersion.Version11;
            request.AllowAutoRedirect = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = referer;
            referer = url;
            request.Host = host;
            //request.ClientCertificates.Clear();
            request.ClientCertificates.Add(clientCertificates);
            request.PreAuthenticate = true;

            this.Status = "Successful";
        }
        catch (Exception ex)
        {
            this.Status = ex.ToString();
        }
        return this.ToString();
    }
    public string SetRequest(string url, string method, string data)
    {
        try
        {
            request = (HttpWebRequest)WebRequest.Create(url);
            if (method.Equals("GET") || method.Equals("POST"))
            {
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
            request.UserAgent = userAgent;
            request.Accept = accept;
            request.Headers.Add(acceptLanguage);
            request.Headers.Add(acceptEncoding);
            request.KeepAlive = true;
            request.CookieContainer = new CookieContainer();
            if (cookieCollection != null)
                request.CookieContainer.Add(cookieCollection);
            request.ProtocolVersion = HttpVersion.Version11;
            request.AllowAutoRedirect = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = referer;
            referer = url;
            request.Host = host;
            //request.ClientCertificates.Clear();
            request.ClientCertificates.Add(clientCertificates);
            request.PreAuthenticate = true;

            byte[] byteArray = Encoding.UTF8.GetBytes(data);
            request.ContentLength = byteArray.Length;
            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            this.Status = "Successful";
        }
        catch (Exception ex)
        {
            this.Status = ex.Message;
        }
        return this.Status;
    }
    public string SetRequest(string url, string method, string data, string contentType)
    {
        try
        {
            request = (HttpWebRequest)WebRequest.Create(url);
            if (method.Equals("GET") || method.Equals("POST"))
            {
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
            request.UserAgent = userAgent;
            request.Accept = accept;
            request.Headers.Add(acceptLanguage);
            request.Headers.Add(acceptEncoding);
            request.KeepAlive = true;
            request.CookieContainer = new CookieContainer();
            if (cookieCollection != null)
                request.CookieContainer.Add(cookieCollection);
            request.ProtocolVersion = HttpVersion.Version11;
            request.AllowAutoRedirect = false;
            request.ContentType = contentType;
            request.Referer = referer;
            referer = url;
            request.Host = host;
            //request.ClientCertificates.Clear();
            request.ClientCertificates.Add(clientCertificates);
            request.PreAuthenticate = true;

            byte[] byteArray = Encoding.UTF8.GetBytes(data);
            request.ContentLength = byteArray.Length;
            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            this.Status = "Successful";
        }
        catch (Exception ex)
        {
            this.Status = ex.Message;
        }
        return this.Status;
    }
    public void Dispose()
    {
        request.Abort();
        request = null;
        dataStream.Close();
        dataStream.Dispose();
        dataStream = null;
    }
}

共有1个答案

夹谷志
2023-03-14

如何将SSL证书引入HttpWebRequest类?

您的问题根本与SSL无关。

private string acceptEncoding = "Accept-Encoding: gzip, deflate, br";
...
        request.Headers.Add(acceptEncoding);

通过这段代码,您可以显式地告诉服务器,您将支持各种内容压缩算法。只是,这是一个谎言,因为你在阅读响应时不处理压缩。

 类似资料:
  • 由于以下错误消息,我无法使用WebRequest连接到HTTPS服务器(TLS 1.3): 请求被中止:无法创建SSL/TLS安全通道。 以前的TLS版本是1.2,使用下面的代码,我可以正确获取页面,但当页面ssl升级到TLS 1.3时,我出现了错误,并且我找不到任何解决方案: 事实上,我认为应该是这样的: 但是没有。

  • 问题内容: hashCode()如何实现? 我的假设是它将对象存储位置用作运行哈希函数的初始数字(种子)。然而,这种情况并非如此。 我还研究了Hash:它在内部如何工作?但它不能回答我的问题。 是的,我可以下载SDK,但是在执行此操作并查看代码之前,也许其他人已经知道了。 谢谢 :) 编辑: 我知道它应该被覆盖等等,所以请尝试保持话题:) 问题答案: 当然,它是特定于实现的,但是通常,对象的哈希码

  • 问题内容: 我很快将使用Java的log4j类来创建项目。但是我不认为我对此有任何了解。希望有人能启发我这个小问题。 问题答案: Log4j基本上接受您要输出的任何语句,让您为其分配“严重性”级别(警告,错误,严重等),并以多种方式将其注销。(对于文件,字节流等,有很多附加选项可用。) 这是对log4j的简短介绍。 http://www.developer.com/open/article.php

  • 本文向大家介绍如何用Python3实现Dictionary,包括了如何用Python3实现Dictionary的使用技巧和注意事项,需要的朋友参考一下 python中的字典是一种数据结构,可将键映射到作为键值对的值。它们是经常使用的数据结构之一,并具有许多有趣的属性。通过将它们括在一对大括号中来呈现它们,如下所示。 字典中的元素或键值对用单引号表示,并用冒号分隔。 创建字典 我们通过分配以键形式编

  • 问题内容: 我从服务器获取响应并使用listview显示它,并且工作正常,现在我正在尝试添加自动完成文本视图以按名称搜索项目,但是当我运行我的应用程序时,它崩溃并显示错误..我已经在问这个 Tab1Activity.java } 自定义适配器 问题答案: 首先创建一个实现可过滤的自定义适配器: 而不是创建一个文本监视器 最后将您的TextWatcher添加到您的搜索编辑文本中: 希望对您有帮助。

  • 问题内容: 我正在使用C#HttpWebRequest来获取网页的一些数据。问题是在页面加载后,使用javascript / ajax更新了某些数据,但我没有在响应字符串中获取它。有没有办法让webrequest等待页面中的所有脚本执行完毕? 谢谢 阿米特 问题答案: 如果我正确解释了您的问题,那么您的问题就没有简单的解决方案。 您正在从服务器上抓取HTML,并且由于C#代码不是真正的Web浏览器