---
title: "Silverlight 中的WebClient 与 WebRequest 示例"
author: "terryfeng"
date: "2010-02-16T16:48:00Z"
tags: []
slug: "silverlight-webclient-webrequest"
draft: false
lastmod: "2010-02-16T16:48:00Z"
id: 595582
url: "https://terryfeng.iteye.com/blog/595582"
---

## **WebClient**

public partial class webclientSample : UserControl  
  {  
      public webclientSample()  
      {  
          InitializeComponent();  
          //定义URL地址  
          string url = "[http://localhost:2365/Sample.web/responseText.htm";](http://localhost:2365/Sample.web/responseText.htm%22;)  
          //创建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";](http://localhost:1398/Sample.web/responseText.htm%22;)  
            //创建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;  
        }  
    }