winphone 网络请求HttpWebRequest


    public partial class newsDetail : PhoneApplicationPage
    {
        public newsDetail()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(LoadNews);

        }

        private void LoadNews(object sender, RoutedEventArgs e)
        {
            string url = NavigationContext.QueryString["url"];
            WebRequest request = HttpWebRequest.Create(url);
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse(ResponseCallBack, request);
        }

        //转换解决汉字乱码问题
        public static string ConvertExtendedASCII(string HTML)
        {
            StringBuilder str = new StringBuilder();
            char c;
            for (int i = 0; i < HTML.Length; i++)
            {
                c = HTML[i];
                if (Convert.ToInt32(c) > 127)
                {
                    str.Append("&#" + Convert.ToInt32(c) + ";");
                }
                else
                {
                    str.Append(c);
                }
            }
            return str.ToString();
        }

        private void ResponseCallBack(IAsyncResult result)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                WebResponse response = request.EndGetResponse(result);

                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    XDocument Xdoc = XDocument.Parse(reader.ReadToEnd());
                    Dispatcher.BeginInvoke(() =>
                    {
                        foreach (var item in Xdoc.Descendants("News"))
                        {
                            tbTitle.Text = item.Element("NewsTitle").Value;
                            tbTime.Text = item.Element("NewsTime").Value;
                            string text = "<html><head></head><body style=\"background-color:White;color:#919191;font-size:18px;margin:10px 20px 10px 20px;\">" + item.Element("NewsContent").Value + "</body></html>";//WebBrowser背景色,字体大小
                            textViewer.NavigateToString(ConvertExtendedASCII(text));
                        }
                    });
                }
            }
            catch (Exception e)
            {
            }
        }

        private void goback_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
        }

    }


你可能感兴趣的:(网络请求,WinPhone,HttpWebRequest)