我想使用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