zoukankan      html  css  js  c++  java
  • Silverlight 中的WebClient 与 WebRequest 示例

    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;
            }
        }

    冯瑞涛
  • 相关阅读:
    如何向线程传递参数
    IntelliJ IDEA 13 Keygen
    单链表的基本操作
    顺序表静态查找
    有向图的十字链表表存储表示
    BF-KMP 算法
    图的邻接表存储表示(C)
    二叉树的基本操作(C)
    VC远控(三)磁盘显示
    Android 数独游戏 记录
  • 原文地址:https://www.cnblogs.com/finehappy/p/1668765.html
Copyright © 2011-2022 走看看