最近在項目中使用pWebRequest 使用NetworkCredential 進行域認證下載時老不成功,最後Google瞭解決方案,發現幾乎所有討論的方案都不成功,只好埋頭自己解決,最後總算調試通過,特將整個解決過程的代碼實現記錄下來,節約大家以後解決類似問題的時間。
KEY POINT: 主要是需要加入ContentType讓Server端能夠正確解碼。
request.ContentType = "application/x-www-form-urlencoded";
具體實現代碼如下:
void DownloadOneFileByHttp(string remoteurl, string localpath, string localurl)
{
HttpWebRequest
request = HttpWebRequest.Create(remoteurl) as HttpWebRequest; WebRequestMethods.Http.Get; false; new NetworkCredential(this.UserName, this.Password, this.Domain); "application/x-www-form-urlencoded"; //very important for authentication
request.Method =
request.PreAuthenticate =
request.Credentials =
request.ContentType =
MemoryStream memStream = new MemoryStream(1024 * 500);
byte[] buffer = new byte[1024];
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream reader = response.GetResponseStream();
// Create the subfolder
if (!System.IO.File.Exists(localpath))
{
System.IO.
Directory.CreateDirectory(localpath);
}
// Write specified bytes array (content) to a file
FileStream newFile = null;
try
{
newFile =
new FileStream(localurl, FileMode.Create);
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if(bytesRead == 0)
{
break;
}
else
{
memStream.Write(buffer, 0, bytesRead);
}
}
if(memStream.Length > 0)
{
// Converts the downloaded stream to a byte array
byte [] downloadedData = memStream.ToArray();
newFile.Write(downloadedData, 0, downloadedData.Length);
}
}
catch (Exception ex)
{
System.
Console.WriteLine("Exception in HTTP downloading: {0}", ex.Message);
}
finally
{
if (newFile != null) newFile.Close();
if (reader != null) reader.Close();
if (response != null) response.Close();
}
}
最後提示一下大家:對於想瞭解為何要這樣寫的朋友可以使用IE登陸並且用httpwatchpro 攔截一下整個報文的內容,然後用.NET代碼訪問並且下載同樣的檔案,然後使用winpcap這樣的網路嗅探器攔截一下整個報文的內容,對比一下你就很容易得出結論。
當然這個解決方案對於熟知HTTP協議並且編寫過自訂爬蟲的朋友是很容易得出。