WP7 网络请求之WebClient
WebClient運行于UI線程,支持編碼方式的設定、支持POST/GET方式提交、不支持同步請求、不支持超時設定。WP7會緩存URL鏈 接,所以兩次請求,盡管網絡端數據發生了變化,得到的還會是同樣的數據,這點要特別注意,避免的方式是在URL的末端,加一個當前時間的參數,這樣每次請 求的url都不一樣,從而避免的緩存的影響。另外要說的是,WebClient不適合大數據量的的請求,那樣會造成UI線程的繁忙,最終導致無法響應用戶 的操作。當然WebClient也有它的優點,因為經過了封裝,用起來方面,也無需做太多的設置,適合小數據量的請求。
實例1:用post方式提交數據
Uri url = new Uri(“http//:www.163.com”);
string str = "name=name1&mo=" + HttpUtility.UrlEncode("中文數據和特殊字符最好編碼一下") + "&Cache=" + System.DateTime.Now;
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.UTF8Encoding.UTF8;
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
//webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(webClient_UploadProgressChanged);//這個是
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(CardInfoUp_Completed);//這里是回調函數
webClient.UploadStringAsync(url, "POST", str);
private void CardInfoUp_Completed(object sender, UploadStringCompletedEventArgs e)
{
if(e.Error==null)
{
// XElement strXml = XElement.Parse(e.Result);//這是網絡返回的數據
MessageBox.Show("成功!");
}
else
{
MessageBox.Show(e.Error.Message);
}
}
如果想代碼更簡潔一些,可以使用匿名函數,像下面這樣:
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.UTF8Encoding.UTF8;
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
webClient.UploadStringCompleted += (s, o) =>
{
if (o.Error == null)
{
//string data=o.Result ;//這是網絡返回的數據
MessageBox.Show("成功");
}
else
{
throw new Exception(o.Error.Message);
}
};
webClient.UploadStringAsync(url, "POST", str);
實例2:打開網頁,可以帶參數,如果服務器返回的內容經過加工,可以使用這種方式變相下載數據
WebClient webClient = new WebClient();
webClient.OpenReadAsync(url); //在不阻止調用線程的情況下,從資源返回數據
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(CardInfoDown_Completed); //異步操作完成時發生
private void CardInfoDown_Completed(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Result))
{
string strStream = reader.ReadToEnd();//這里是返回的數據
MessageBox.Show("下載成功");
}
}
else
{
MessageBox.Show(e.Error.Message);
}
}
下面是簡潔的寫法:
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.UTF8Encoding.UTF8;
webClient.OpenReadAsync(url); //在不阻止調用線程的情況下,從資源返回數據
webClient.OpenReadCompleted += (s,o) =>
{
if (o.Error == null)
{
//指定以UTF-8方式讀取流
using (System.IO.StreamReader reader = new System.IO.StreamReader(o.Result, System.Text.UTF8Encoding.UTF8))
{
string strStream = reader.ReadToEnd();//這里是返回的數據
MessageBox.Show("下載成功");
}
}
else
{
MessageBox.Show(o.Error.Message);
}
};
實例2:下載數據,這個暫時還沒用到,先預留位置在此
?
http://www.cnblogs.com/dyg540/articles/2514773.html
轉載于:https://www.cnblogs.com/zziss/archive/2012/10/23/2736018.html
總結
以上是生活随笔為你收集整理的WP7 网络请求之WebClient的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql server :distinct
- 下一篇: 天外键盘映射工具(适合魔兽真三改键)