HTTP通信之download方法

1.public void DownloadFile(string localFile, string downloadUrl)

2.HttpWebRequest req = (HttpWebRequest)WebRequest.Create(downloadUrl);
  req.Method = "GET";

3.HttpWebResponse resp = (HttpWebResponse) req.GetResponse();

4 .Stream respStream = resp.GetResponseStream();

5 .whole method:

public void DownloadFile(string localFile, string downloadUrl)
{
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(downloadUrl);
  req.Method = "GET";
 
  HttpWebResponse resp = (HttpWebResponse) req.GetResponse();

  // Retrieve response stream and wrap in StreamReader
  Stream respStream = resp.GetResponseStream();
  StreamReader rdr = new StreamReader(respStream);

  // Create the local file
  StreamWriter wrtr = new StreamWriter(localFile);

  // loop through response stream reading each line 
  // and writing to the local file
  string inLine = rdr.ReadLine();
  while (inLine != null)
  {
    wrtr.WriteLine(inLine);
    inLine = rdr.ReadLine();
  }

  rdr.Close();
  wrtr.Close();
}
6.由于以上程序只能下载文本文件,为了下载其他格式的文件,要用到以下代码:
public void DownloadFileBinary(string localFile, string downloadUrl)
{
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(downloadUrl);
  req.Method = "GET";

  HttpWebResponse resp = (HttpWebResponse) req.GetResponse();

  // Retrieve response stream
  Stream respStream = resp.GetResponseStream();

  // Create local file
  FileStream wrtr = new FileStream(localFile, FileMode.Create);

  // Allocate byte buffer to hold stream contents
  byte[] inData = new byte[4096];

  // loop through response stream reading each data block
  //  and writing to the local file
  int bytesRead = respStream.Read(inData, 0, inData.Length);
  while (bytesRead > 0)   //等于0,表示读完
  {
    wrtr.Write(inData, 0, bytesRead);
    bytesRead = respStream.Read(inData, 0, inData.Length);
  }

  respStream.Close();
  wrtr.Close();
}
7.Creating DownloadButton:
private void downloadButton_Click(object sender, System.EventArgs e) 
{ 
DownloadFileBinary(localFileTextBox.Text, urlTextBox.Text); 
}
8.在localFileTextBox里输入http.html,
在urlTextBox里输入http://www.cnblogs.com/moonknight/articles/26812.html(这是这篇文章的参考资料的url)。
按下downloadButton后,会把网页存到“我的移动设备”,文件名为“http.html”。
补充一下:以上类用到了System.Net和System.IO(其实点一下类系统会自己生成)。
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s