现在的位置: 首页 > 综合 > 正文

window phone WebClient和HttpWebRequest 并解决gb2312乱码问题

2012年09月04日 ⁄ 综合 ⁄ 共 1778字 ⁄ 字号 评论关闭

1.WebClient类

在System.Net空间下,提供向URI标识的目标发送数据和从URI标识的目标接收数据的类。

获取数据通过OpenReadAync,完成时OpenReadCompleted

private void DoWebClient()
        {
            string url = "http://www.qq.com";
            WebClient client = new WebClient();
            client.OpenReadAsync(new Uri(url));
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(WebClient_OpenReadCompleted);
        }
        private void WebClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            using (StreamReader reader = new StreamReader(e.Result,DBCSCodePage.DBCSEncoding.GetDBCSEncoding("gb2312")))
            {
                string contents = reader.ReadToEnd();
                int begin = contents.ToString().IndexOf("<title>");
                int end = contents.ToString().IndexOf("</title>");
                //UI线程调用,直接更新界面
                ClientText.Text = contents.ToString().Substring(begin + 7, end - begin - 7);
            }
        }

2.HttpWebRequest 类

在System.Net空间下,提供WebRequest类的HTTP的实现

private void DoHttpWebRequest()
        {
            string url = "http://www.baidu.com";
            WebRequest request = HttpWebRequest.Create(url);
            IAsyncResult result = request.BeginGetResponse(ResponseCallBack, request);
        }

        private void ResponseCallBack(IAsyncResult result)
        {
            
            HttpWebRequest req = result.AsyncState as HttpWebRequest;
            WebResponse res = req.EndGetResponse(result);
            using(Stream stream=res.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream, DBCSCodePage.DBCSEncoding.GetDBCSEncoding("gb2312")))
            {
                string contents = reader.ReadToEnd();
                int begin = contents.ToString().IndexOf("<title>");
                int end = contents.ToString().IndexOf("</title>");
                //基于后台运行,不在UI线程
                Dispatcher.BeginInvoke(() => { ReqText.Text = contents.ToString().Substring(begin + 7, end - begin - 7); });
            }
            
        }

ps:DBCSCodePage就是用来解决乱码问题的

源码:http://download.csdn.net/detail/wulongtiantang/5072852

抱歉!评论已关闭.