WebClient
public partial class webclientSample : UserControl
{
public webclientSample()
{
InitializeComponent();
//定义URL地址
string url = "http://localhost:2365/Sample.web/responseText.htm";
//创建WebClient对象
WebClient webClient = new WebClient();
//定义异步请求地址
webClient.DownloadStringAsync(new Uri(url
, UriKind.RelativeOrAbsolute));
//定义请求完成的事件处理
webClient.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler
(webClient_DownloadStringCompleted);
}
private void webClient_DownloadStringCompleted(object sender
, DownloadStringCompletedEventArgs e)
{
//显示返回值
MessageBox.Show(e.Result.ToString());
}
}
WebRequest
public partial class webrequestSample : UserControl
{
//定义异步委托方法
private delegate void DispatcherInvoke(string str);
public webrequestSample()
{
InitializeComponent();
//定义URL地址
string url = "http://localhost:1398/Sample.web/responseText.htm";
//创建WebClient对象
WebRequest request =
HttpWebRequest.Create(new Uri(url
, UriKind.RelativeOrAbsolute));
//开始获取响应并进行异步回调
request.BeginGetResponse(new AsyncCallback(responseReady)
, request);
}
private void responseReady(IAsyncResult ar)
{
//返回异步回调结果对象
WebRequest request = ar.AsyncState as WebRequest;
//获取结果响应对象
WebResponse response = request.EndGetResponse(ar);
//定义返回流对象
using (Stream stream = response.GetResponseStream())
{
//使用流读取对象
StreamReader reader = new StreamReader(stream);
//*** 直接读取将发生错误。
//tbk.Text = "reader.ReadToEnd();
//使用Dispatcher异步执行委托方法
tb.Dispatcher.BeginInvoke
((DispatcherInvoke)processResult
, reader.ReadToEnd());
}
}
private void processResult(string result)
{
//显示返回字符串
tb.Text = result;
}
}