string formUrl = "url";
string formParams = string.Format("params");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
string getUrl = "link to csv file";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
嘿伙计们,我目前正在使用此代码,我从这个网站上下载,我已经下载了fiddler并且能够登录并导航到我想要下载我的.csv文件的页面。
StreamReader会带回.csv文件中的内容,但我想将其下载到计算机上的路径中。
getUrl是一个直接链接到我在浏览器中单击下载文件的链接。
网址示例: http://myurl.com/index.php?controller=AdminRequestSql&token=123&id_request_sql=7&exportrequest_sql=1
很抱歉,如果措辞不正确,我对C#很陌生并试图学习新东西。
由于
答案 0 :(得分:1)
对于.NET Framework 4及更高版本:
string formUrl = "url";
string formParams = string.Format("params");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
string getUrl = "link to csv file";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new
using (Stream output = File.OpenWrite("filename.csv"))
using (Stream input = getResponse.Response.GetResponseStream())
{
input.CopyTo(output);
}
对于低于4的.NET框架
using (Stream output = File.OpenWrite("filename.csv"))
using (Stream input = getResponse.Response.GetResponseStream())
{
byte[] buffer = new byte[8192];
int bytesLength;
while ((bytesLength = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesLength);
}
}
两者之间的区别在于您需要手动下载较低框架的文件。此外,建议使用WebClient
类。您可以找到有关如何使用该类的大量资源。目前,您可以开始使用here。