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

    冯瑞涛
  • 相关阅读:
    LDAP安装配置(windows)
    chrome postman插件手动安装
    mabatis insert into on duplicate key
    ZOJ 3641 <并查集+STL>
    ZOJ 3633 <rmq 重点在于转化>
    POJ 2817 状态DP 字符串找最多的重复
    POJ 2771 简单二分图匹配
    POJ 1149 最大流<建图> PIGS
    POJ 3692 二分图最大独立点集
    POJ 2239 简单的二分图求最大匹配
  • 原文地址:https://www.cnblogs.com/finehappy/p/1668765.html
Copyright © 2020-2023  润新知