编程语言
首页 > 编程语言> > C#https登录并下载文件

C#https登录并下载文件

作者:互联网

我已经成功连接到登录页面,但是,我不确定如何登录并获取登录背后的文件.下面是我用来建立连接的代码.

  private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
    {
        return true;
    }


    public static void Processing()
    {
        string url = "https://app/templat";
        HttpWebRequest request;
        HttpWebResponse response;
        CookieContainer cookies;
        ServicePointManager.ServerCertificateValidationCallback =
        System.Net.ServicePointManager.ServerCertificateValidationCallback =
        ((sender, certificate, chain, sslPolicyErrors) => true);
        System.Net.ServicePointManager.ServerCertificateValidationCallback
            = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));
        ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(bypassAllCertificateStuff);
        try
        {
            request = (HttpWebRequest)WebRequest.Create(url);
            request.AllowAutoRedirect = false;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                cookies = request.CookieContainer;



                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                String postData = "j_login=user&j_password=user&submit=Send";
                byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(postData);
                request.ContentLength = data.Length;
                //Stream stream = request.GetRequestStream();
                //stream.Write(data, 0, data.Length);

                request.CookieContainer = cookies;

                //stream.Close();
                StreamReader sr = new StreamReader(response.GetResponseStream());
                string tmp = sr.ReadToEnd().Trim();


                //response = (HttpWebResponse)request.GetResponse();
                //WebClient wbClient = new WebClient();
                //wbClient.DownloadFile("https://app/template/simple%2Screen.vm", @"C:\test.xls");

                response.Close();
            }
            else
            {
                Console.WriteLine("Client was unable to connect!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

    }

我很肯定下载无法正常进行,并且我确定String postData不会执行预期的操作.

以下是网站登录代码

<pre>
<form name=\"loginform\" method=\"post\" action=\"j_security_check\" onSubmit=\"javascript:fixFields();\">
<br>
<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"80%\">
<tr>
<td colspan=\"2\" align=\"center\" nowrap=\"nowrap\">
<div id=\"bannerDiv\" class=\"groupingBorder\" style=\"visibility:hidden;position:relative;background-color:#FFFFFF; overflow:auto;\">
</div>
</td>

</tr>
<tr>
<td class=\"contentrtanbld\" nowrap width=\"50%\">Name:</td>
 <td class=\"contentltan\" nowrap width=\"50%\">
<input type=\"text\" name=\"j_username\" id=\"j_username\" value=\"\" class=\"authGroupWidth\" size=\"20\"></td>
 </tr>
<tr>
<td class=\"contentrtanbld\" nowrap>Password:</td>
<td class=\"contentltan\" nowrap>
<input type=\"password\" name=\"j_password\" id=\"j_password\" value=\"\" class=\"authGroupWidth\" size=\"20\"></td>
</tr>
<tr>
</pre>

我要下载的文件是通过此链接
https://app/template/simple%2Screen.vm

我可以建立与网页的连接,但不确定如何登录和下载文件.

请查看代码更新.这仍然没有登录,我不确定为什么.

 string url = "https://mgr/app";
        HttpWebRequest request;
        HttpWebResponse response;
        CookieContainer cookies = new CookieContainer();
        ServicePointManager.ServerCertificateValidationCallback =
        System.Net.ServicePointManager.ServerCertificateValidationCallback =
        ((sender, certificate, chain, sslPolicyErrors) => true);
        System.Net.ServicePointManager.ServerCertificateValidationCallback
            = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));
        ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(bypassAllCertificateStuff);
        try
        {
            string cookieHeader;
            string formParams = string.Format("j_login={0}&j_password={1}", "user", "user");
            request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(formParams);
            request.ContentLength = bytes.Length;
            using (Stream os = request.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            WebResponse resp = request.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];

            string pageSource;
            string BehinPath = "https://mgr/app/action/store.VivolAction/eventsubmit_dopreparevivollist/ignored";
            WebRequest getRequest = WebRequest.Create(BehinPath);
            getRequest.Headers.Add("Cookie", cookieHeader);
            WebResponse getResponse = getRequest.GetResponse();
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
            }

这是新代码,有1个cookie,但是当我尝试第一篇文章时,它永远不会登录.

解决方法:

您的代码有以下问题,我可以看到:

>无法正确处理Cookie容器.应该初始化CookieContainer,然后将其传递给您的HttpWebRequest,而不是相反.
>不清理一次性物品.未能放置对象可能导致该对象在垃圾收集器赶上它之前徘徊了一段时间.
>不考虑表单操作.您的表单操作将导致提交到其他位置.
>不必要以POST形式执行第一个操作.改用GET.
>执行POST操作时不设置参照.

尝试以下代码:

    Uri url = new Uri("http://app/templat");
    HttpWebRequest request = null;

    // Uncomment the line below only if you need to accept an invalid certificate, i.e. a self-signed cert for testing.
    // ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
    CookieContainer cookieJar = new CookieContainer();

    request = (HttpWebRequest)WebRequest.Create(url);
    request.CookieContainer = cookieJar;
    request.Method = "GET";
    HttpStatusCode responseStatus;

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        responseStatus = response.StatusCode;
        url = request.Address;
    }

    if (responseStatus == HttpStatusCode.OK)
    {
        UriBuilder urlBuilder = new UriBuilder(url);
        urlBuilder.Path = urlBuilder.Path.Remove(urlBuilder.Path.LastIndexOf('/')) + "/j_security_check";

        request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
        request.Referer = url.ToString();
        request.CookieContainer = cookieJar;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        using (Stream requestStream = request.GetRequestStream())
        using (StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
        {
            string postData = "j_username=user&j_password=user&submit=Send";
            requestWriter.Write(postData);
        }

        string responseContent = null;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader responseReader = new StreamReader(responseStream))
        {
            responseContent = responseReader.ReadToEnd();
        }

        Console.WriteLine(responseContent);
    }
    else
    {
        Console.WriteLine("Client was unable to connect!");
    }       

标签:httpwebresponse,httpwebrequest,c
来源: https://codeday.me/bug/20191101/1984367.html