C#HTTPS登录和下载文件 [英] C# https login and download file

查看:413
本文介绍了C#HTTPS登录和下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须成功连接到登录页面,不过,我不知道如何登录并抓住登录背后的文件多数民众赞成。下面是code我使用,使连接。

I have successful connected to the login page, however, i'm not sure how to login and grab the file thats behind the login. Below is the code i'm using to make the connect.

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

    }

我肯定下载不工作,我敢肯定,字符串POSTDATA 不执行该怎么打算。

下面是code的网站登录

Below is the code for the website login

<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

And the file I want to download is via this link https://app/template/simple%2Screen.vm

我能做出的网页连接,但我不能确定如何登录并下载该文件。

I'm able to make the connection to the webpage but i'm unsure how to login and download the file.

请参阅更新code。这还没有登录,我不知道为什么。

Please see update to code. This is still not logging in and i'm not sure why.

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

这是新的code,有1 cookie的,但是当我尝试后的第一个它从未记录。

This is the new code, there is 1 cookie, however when i try the first post it never logs in.

推荐答案

您code,存在以下问题,我可以看到:

Your code has the following problems that I can see:


  1. 不能正确处理cookie的容器。的CookieContainer应该初始化,然后传递到你的HttpWebRequest的,而不是其他的方式。

  2. 不清理支配的对象。如果不处置的对象可能会导致挂在相当长的一段垃圾收集与它赶上之前的对象。

  3. 不占表单操作。你的表单操作会导致提交到不同的位置。

  4. 进行不必要的第一个操作为POST。使用GET来代替。

  5. 执行POST操作时,不设置引荐。

请尝试以下code:

    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!");
    }       

这篇关于C#HTTPS登录和下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆