gpt4 book ai didi

C# https登录并下载文件

转载 作者:行者123 更新时间:2023-11-30 15:39:55 24 4
gpt4 key购买 nike

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

  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,但是当我尝试第一个帖子时它从未登录。

最佳答案

您的代码存在以下我能看到的问题:

  1. 没有正确处理 cookie 容器。 CookieContainer 应该被初始化,然后传递给您的 HttpWebRequest,而不是相反。
  2. 不清理一次性元素。未能处置对象可能会导致该对象在垃圾收集器追上它之前停留很长一段时间。
  3. 不考虑表单操作。您的表单操作将导致提交到不同的位置。
  4. 不必要地将第一个操作作为 POST 执行。请改用 GET。
  5. 执行 POST 操作时不设置 referer。

试试下面的代码:

    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登录并下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9841344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com