我正在尝试使用 webrequest 方法加载文件。首先我需要登录然后获取文件或目录列表。https:///xxx.yyy.zzz/login_template
当我在 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();
}
我得到的响应是好的 - 所以我似乎成功登录了。但是,我需要去另一个 url 来获取文件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: The remote server returned an error: (501) Not Implemented。在 System.Net.HttpWebRequest.GetResponse()
我已经阅读了所有我能找到的关于这个错误的信息——似乎问题应该出在我得到的方式上——请求中有一些东西在服务器上没有得到正确处理——但我看不出是什么是错的。