windows phone 访问google天气预报

/*
pivot.xaml.cs
*/
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.IO; using HtmlExtractor; using System.Xml.Linq; namespace IMove { public partial class PivotPage1 : PhoneApplicationPage { private static String cityName = "Beijing"; public PivotPage1() { InitializeComponent(); LoadWeatherInformation(); } private void LoadWeatherInformation() { OnlineUpdate(); } private void OnlineUpdate() { UriBuilder uri = new UriBuilder("http://www.google.com/ig/api"); uri.Query = "weather=" + cityName+ "&hl=zh-cn";// 如果不加&后面的话,返回的是英文的页面
        
        
        //然后是用HttpWebRequest访问google api HttpWebRequest forecastRequest = (HttpWebRequest)WebRequest.Create(uri.Uri); forecastRequest.BeginGetResponse(new AsyncCallback(ForecastResponseCallback), forecastRequest); } private void ForecastResponseCallback(IAsyncResult asynchronousResult) { HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult); Stream streamResponse = webResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(streamResponse,new Gb2312Encoding());//注意gb2312在windows phone里面目前没有,需要自己加入两个文件 String content = streamReader.ReadToEnd(); LinkedList<WeatherInfoUnit> weatherList = SplitWeatherInfo(content.Replace('\0',' ').Trim());//末尾出现很多'\0',导致xml解析失败 Dispatcher.BeginInvoke(() => UpdateWeatherText(weatherList)); streamReader.Close(); streamResponse.Close(); webResponse.Close(); } private void UpdateWeatherText(LinkedList<WeatherInfoUnit> weatherList) { WeatherInfoUnit curWeather = weatherList.ElementAt(0); runHumidity.Text = curWeather.Humidity; runTemperature.Text = curWeather.Low ; runWeather.Text = curWeather.Condition; WeatherInfoUnit curWeather1 = weatherList.ElementAt(1); textWeather1.Text = curWeather1.Date + "\n" + curWeather1.Low + " / " + curWeather1.High + " ℃\n" + curWeather1.Condition + "\n" ; WeatherInfoUnit curWeather2 = weatherList.ElementAt(2); textWeather2.Text = curWeather2.Date + "\n" + curWeather2.Low + " / " + curWeather2.High + " ℃\n" + curWeather2.Condition + "\n"; WeatherInfoUnit curWeather3 = weatherList.ElementAt(3); textWeather3.Text = curWeather3.Date + "\n" + curWeather3.Low + " / " + curWeather3.High + " ℃\n" + curWeather3.Condition + "\n"; } private LinkedList<WeatherInfoUnit> SplitWeatherInfo(String content) { LinkedList<WeatherInfoUnit> weatherList = new LinkedList<WeatherInfoUnit>(); XElement xmlWeather = XElement.Parse(content); // extract current weather XElement currentConditions = xmlWeather.Descendants("current_conditions").First(); WeatherInfoUnit curWeather = new WeatherInfoUnit(); curWeather.Condition =(String) currentConditions.Element("condition").Attribute("data"); curWeather.Low = (String)currentConditions.Element("temp_c").Attribute("data"); curWeather.High = (String)currentConditions.Element("temp_c").Attribute("data"); curWeather.Icon = (String)currentConditions.Element("icon").Attribute("data"); String stringHumidity =(String)currentConditions.Element("humidity").Attribute("data"); String stringHumidityPrix = "湿度:"; curWeather.Humidity = stringHumidity.Substring(stringHumidityPrix.Length); curWeather.Date = "今天"; weatherList.AddLast(curWeather); foreach (XElement element in xmlWeather.Descendants("forecast_conditions")) { curWeather = new WeatherInfoUnit(); curWeather.Condition = (String)element.Element("condition").Attribute("data"); curWeather.Low = (String)element.Element("low").Attribute("data"); curWeather.High = (String)element.Element("high").Attribute("data"); curWeather.Icon = (String)element.Element("icon").Attribute("data"); curWeather.Date = (String)element.Element("day_of_week").Attribute("data"); weatherList.AddLast(curWeather); } return weatherList; } } }

 

很简单的从google api 抓取xml数据做成的天气预报
设计httpwebrequest请求和xml解析
windows phone 的c# 与.net 有一些不同,多了很多限制,比如支持的Encoding很有限,连gb2312都没有。
附近有两个jpg文件,下载后把后缀换回.cs 加入工程中

 

pivot.xaml
View Code
<phone:PhoneApplicationPage 
    x:Class="IMove.PivotPage1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait"  Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <!--Pivot Control-->
        <controls:Pivot Title="I Move , So happy!">
            <!--Pivot item one-->
            <controls:PivotItem Header="主页">
                <Grid>                   
                     
                    <Canvas>
                        <TextBlock
                        TextWrapping="Wrap"
                        Style="{StaticResource PhoneTextLargeStyle}">
                        <Run x:Name="WelcomeTimeMark" >早上好,</Run>

                        </TextBlock>
                        
                        <TextBlock x:Name="WeatherInfo" Canvas.Left="30" Canvas.Top="69" Height="134" Width="206">
                          <Run>
                                当前天气
                          </Run>
                            <Run x:Name="runWeather">
                                
                            </Run>
                            <LineBreak/>
                            <Run>
                                气温
                            </Run>
                            <Run x:Name="runTemperature">
                                  _ _
                            </Run>
                            <Run></Run>
                            <LineBreak/>
                            <Run>
                                湿度:
                            </Run>
                            <Run x:Name="runHumidity">
                                
                            </Run>
                            

                         </TextBlock>
                        <Image x:Name="WeatherImg" Canvas.Left="302" Canvas.Top="76" Height="116" Width="127">
                            
                        </Image>
                        <TextBlock Canvas.Left="26" Canvas.Top="220" Height="96" Name="textWeather1" Text="Loading" Width="110" />
                        <TextBlock Canvas.Left="171" Canvas.Top="220" Height="96" Name="textWeather2" Text="Loading" Width="110" />
                        <TextBlock Canvas.Left="322" Canvas.Top="220" Height="96" Name="textWeather3" Text="Loading" Width="110" />
                    </Canvas>
                </Grid>
            </controls:PivotItem>

            <!--Pivot item two-->
            <controls:PivotItem Header="item2">
                <Grid/>
            </controls:PivotItem>

            <!--Pivot item three.-->
            <controls:PivotItem Header="item3">
                <Grid/>
            </controls:PivotItem>

        </controls:Pivot>
    </Grid>

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton x:Name="appbar_button2" IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem x:Name="menuItem1" Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem x:Name="menuItem2" Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

两个Encoding文件:

posted on 2012-04-18 21:20  leavingseason  阅读(358)  评论(0)    收藏  举报

导航

Bye!