我想使用webrequest方法加载文件。首先,我需要登录然后获取文件或目录列表。 https:///xxx.yyy.zzz/login_templatewebrequest get引发异常“远程服务器返回错误:(501)未实现”。
当我看到在Firefox网页源,我看到
<META http-equiv="Content-Type" content="text/html">
....
<form method="post" action="/template/login" enctype="application/x-www-form- urlencoded">
....
<input name="user" type="text">
<input name="password" type="password">
<input type=hidden name="switch" value="Log In">
<input type="submit" value="Accept">
所以,我写了这个代码:
public static string DownloadFile()
{
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https:///xxx.yyy.zzz/login_template");
request.CookieContainer = cookieJar;
// Set the credentials.
request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
request.Credentials = new NetworkCredential(userName, pass);
request.KeepAlive = true;
request.UserAgent = "SecureTransport";
request.ContentType = @"application/x-www-form-urlencoded";
request.Method = WebRequestMethods.Http.Post;
bool loggedin = false;
try
{
// first need to log in
string postData = "user=" + userName + "&Password=" + pass;
byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
request.ContentLength = postBuffer.Length;
Stream newStream = request.GetRequestStream();
// Send the data.
newStream.Write(postBuffer, 0, postBuffer.Length);
newStream.Close();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Get the stream containing content returned by the server.
if (response.StatusCode == HttpStatusCode.OK)
{
loggedin = true;
}
response.Close();
}
,我得到的回应是OK - 如此看来,我成功登录了。 但是后来我需要去另外一个网址才能得到一个文件https:///xxx.yyy.zzz/myfile.zip
HttpWebRequest requestToGetFile = (HttpWebRequest)WebRequest.Create("https:///xxx.yyy.zzz/myfile.zip");
requestToGetFile.Method = WebRequestMethods.Http.Get;
requestToGetFile.CookieContainer = cookieJar;
requestToGetFile.UserAgent = "SecureTransport";
requestToGetFile.ContentType = @"application/octet-stream";
using (HttpWebResponse responseToGetFile = (HttpWebResponse)requestToGetFile.GetResponse())
{
if (responseToGetDir.StatusCode != HttpStatusCode.OK)
{
...
}
}
我总是得到一个异常System.Exception:System.Net.WebException:远程服务器返回一个错误:(501)未实现。在System.Net.HttpWebRequest.GetResponse()
我已经阅读了所有我能找到关于这个错误 - 看来问题应该以我得到的方式 - 请求中有东西,它不是在服务器上正确处理 - 但我不明白什么是错的。
将您的请求与使用Fiddler的真实浏览器的请求进行比较。 – SLaks 2011-01-20 19:30:04