英:http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
中:http://msdn.microsoft.com/zh-tw/library/system.net.webclient.aspx
先做個簡單的程式來學學網路應用程式,System.Net內的類別當中,我先用最高層次的類別來玩玩看,這個類別是WebClient,只能讓你當作client來使用。
控制項
- requestTextBox=輸入的網址
- messageTextBox=訊息輸出
try
{
//取得URI識別
Uri thisUri = new Uri(requestTextBox.Text);
WebClient thisWebClient = new WebClient();
//設定快取原則
thisWebClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
//設定用於上載和下載字串的Encoding
thisWebClient.Encoding = Encoding.UTF8;
//下載回應的body資料為string,呼叫DownloadString這會開始執行下載動作
String thisDownloadString = thisWebClient.DownloadString(thisUri);
//取得回應的header資料
messageTextBox.Text += thisWebClient.ResponseHeaders.ToString() + Environment.NewLine;
messageTextBox.Text += thisDownloadString + Environment.NewLine;
//將多行的TextBox移到最後一列
messageTextBox.Select(messageTextBox.Text.Length, 0);
messageTextBox.ScrollToCaret();//將控制項的內容捲動到目前插入號的位置
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//clean up
}
上述是同步(Synchronous)的方式,程式需等待下載命令執行完之後,才能繼續run,你的成是有可能會當掉鎖住,解決方式就是使用非同步(Asynchronous )方式,非同步方法不會封鎖呼叫執行緒。
try
{
//取得URI識別
Uri thisUri = new Uri(requestTextBox.Text);
WebClient thisWebClient = new WebClient();
//設定快取原則
thisWebClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
//設定用於上載和下載字串的Encoding
thisWebClient.Encoding = Encoding.UTF8;
//委派處理WebClient的DownloadStringCompleted 事件的方法
thisWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(thisWebClient_DownloadStringCompleted);
//呼叫DownloadString這會開始執行下載動作
thisWebClient.DownloadStringAsync(thisUri);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//clean up
}
void thisWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//throw new NotImplementedException();
try
{
//取得回應的body資料
String thisDownloadString = e.Result.ToString() + Environment.NewLine;
//取得回應的header資料
messageTextBox.Text += ((WebClient)sender).ResponseHeaders.ToString() + Environment.NewLine;
messageTextBox.Text += thisDownloadString + Environment.NewLine;
//將多行的TextBox移到最後一列
messageTextBox.Select(messageTextBox.Text.Length, 0);
messageTextBox.ScrollToCaret();//將控制項的內容捲動到目前插入號的位置
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//clean up
}
}
沒有留言:
張貼留言