尝试使用HttpWebRequest和响应对象下载文件。 响应不是实际文件,而是返回登录屏幕的HTML。
这是我的代码:
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
string Url = "https://myurl/filename.pdf";
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
fileReq.Timeout = 1000000;
fileReq.KeepAlive = true;
string userID= "emailid";
string Password= "password";
//string credentials = "emailid:password";
//fileReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
fileReq.PreAuthenticate = true;
fileReq.Headers.Add("user", userID);
fileReq.Headers.Add("pass", Password);
//CredentialCache wrCache =
// new CredentialCache();
//wrCache.Add(new Uri(Url), "Basic",
// new NetworkCredential(userID, Password));
//fileReq.Credentials = wrCache;
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
string resultString = string.Empty;
using (Stream rstream = fileResp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(rstream))
{
rstream.Flush();
resultString = sr.ReadToEnd();
}
}
resultString,是pdf文件所在网站的登录页面的HTML。
我已经尝试了几种方法(在上面的代码中注释)来传递用户ID和密码,没有工作。
我可以使用具有相同用户ID和密码的浏览器中的URL直接下载文件