HTTP 通信之upload方法

1.Building an HTTP Client

HTTP 通信需要两个类:HttpWebRequestHttpWebResponse。它们分别可以向服务器发送请求(HttpWebRequest)及接收响应(HttpWebResponse)。

2.Creating the Upload Functions

public void UploadFile(string localFile , string uploadUrl)

UploadFile 有两个 string 参数,第一个是本地文件地址、 第二个是服务器的URL。

3.创建HttpWebRequest类的一个对象:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);

服务器的地址(uploadUrl)可以是:http://192.168.1.102/HttpFileXferVdir/Test.dat

4.把请求的方法设为“PUT”:

req.Method = "PUT";

5.先把数据以Streaming形式写入缓冲区,再打包成StreamWriter进行操作:

Stream reqStream = req.GetRequestStream();

StreamWriter wrtr = new StreamWriter(reqStream);

6.数据写入缓存后,用GetResponse方法得到服务器响应:

Req.GetResponse();

7.用StreamReader读出数据并写入StreamWriter

最终得到如下语句:

public void UploadFile(string localFile, string uploadUrl)
{
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
  req.Method = "PUT";
  req.AllowWriteStreamBuffering = true;

  // Retrieve request stream and wrap in StreamWriter
  Stream reqStream = req.GetRequestStream();
  StreamWriter wrtr = new StreamWriter(reqStream);

  // Open the local file
  StreamReader rdr = new StreamReader(localFile);

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

  rdr.Close();
  wrtr.Close();

  req.GetResponse();
}
8.创建uploadButton来执行方法:
private void uploadButton_Click(object sender, System.EventArgs e) 
{ 
UploadFile(localFileTextBox.Text, urlTextBox.Text); 
}
其中第一个textbox中写入本地文件名,第二个textbox中写入服务器文件的URL。
参考资料:http://www.cnblogs.com/moonknight/articles/26812.html
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