HttpWebRequest 使用NetworkCredential 進行域認證下載時不成功 的解決方案

來源:互聯網
上載者:User

最近在項目中使用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協議並且編寫過自訂爬蟲的朋友是很容易得出。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.