Yahoo Weather API не может подключиться к С#

Yahoo Weather API изменил URL-адрес на этой неделе, и теперь мое приложение не может подключиться. См. ниже код с новым URL-адресом и ниже в комментарии со старым URL-адресом.

private void GetWeather()
{
    try
    {
        string query = String.Format("https://query.yahooapis.com/v1/public/yql?q=" + Settings.Default.WOEID.ToString() + "&u=" + Settings.Default.Temperature);
        //string query = String.Format("https://weather.yahooapis.com/forecastrss?w=" + Settings.Default.WOEID.ToString() + "&u=" + Settings.Default.Temperature);
        XmlDocument wData = new XmlDocument();
        wData.Load(query);

        XmlNamespaceManager man = new XmlNamespaceManager(wData.NameTable);
        man.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

        XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
        XmlNodeList nodes = wData.SelectNodes("/query/results/channel/item/yweather:forecast", man);
        //XmlNodeList nodes = wData.SelectNodes("/rss/channel/item/yweather:forecast", man);

        Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", man).Attributes["temp"].Value;

        Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", man).Attributes["text"].Value;

        Humidity = channel.SelectSingleNode("yweather:atmosphere", man).Attributes["humidity"].Value;

        WinSpeed = channel.SelectSingleNode("yweather:wind", man).Attributes["speed"].Value;

        Town = channel.SelectSingleNode("yweather:location", man).Attributes["city"].Value;

        TFCond = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", man).Attributes["text"].Value;

        TFHigh = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", man).Attributes["high"].Value;

        TFLow = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", man).Attributes["low"].Value;

        QEvent = "connected";
    }
    catch { QEvent = "failed"; }
}

Я получаю следующую ошибку:

Исключение: Возникло исключение: «System.Net.WebException» в System.dll («Удаленный сервер вернул ошибку: (400) неверный запрос».). Возникло исключение: «System.Net.WebException» в System.dll («Удаленный сервер вернул ошибку: (400) неверный запрос».) 12,32 с [11632]


person Peter Smeets    schedule 28.07.2017    source источник
comment
То, что вы отправляете в службу, также должно измениться. Проверьте их документацию по API, чтобы узнать, какие поля у вас отсутствуют или были переименованы.   -  person    schedule 28.07.2017
comment
Каждый раз, когда кто-то использует описанный выше антишаблон обработки исключений, бог убивает котенка.   -  person Uwe Keim    schedule 28.07.2017
comment
@Amy Документация по API устарела, и я не знаю, какие поля мне не хватает или их нужно изменить.   -  person Peter Smeets    schedule 29.07.2017
comment
@UweKeim Я впервые использую C#, и я не нахожу способа поймать исключение или выполнить отладку в Visual Studio, я понимаю, что это может показаться вам глупым, но небольшая помощь в том, как действовать, помогла бы мне больше, чем этот комментарий ;)   -  person Peter Smeets    schedule 29.07.2017
comment
@PeterSmeets Настройте отладчик VS на остановку при возникновении исключений.   -  person Uwe Keim    schedule 29.07.2017


Ответы (2)


Попробуйте изменить URL на

string query = String.Format("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(" + Settings.Default.WOEID.ToString() + ")%20and%20u%20%3D%20%27" + Settings.Default.Temperature + "%27&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");

РЕДАКТИРОВАТЬ:

Я не знаю, где документация, но это URL.
дает

<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="1" yahoo:created="2017-07-31T17:50:38Z" yahoo:lang="en-US">
<results>
<channel>
<yweather:units xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" 
distance="mi" pressure="in" speed="mph" temperature="F"/>
<title>Yahoo! Weather - Seattle, WA, US</title>
<link>
http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2490383/
</link>
<description>Yahoo! Weather for Seattle, WA, US</description>
<language>en-us</language>
<lastBuildDate>Mon, 31 Jul 2017 10:50 AM PDT</lastBuildDate>
<ttl>60</ttl>
<yweather:location xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" city="Seattle" country="United States" region=" WA"/>
<yweather:wind xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" chill="66" direction="0" speed="14"/>
<yweather:atmosphere xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" humidity="64" pressure="1023.0" rising="0" visibility="16.1"/>
<yweather:astronomy xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" sunrise="5:45 am" sunset="8:45 pm"/>
<image>
<title>Yahoo! Weather</title>
<width>142</width>
<height>18</height>
<link>http://weather.yahoo.com</link>
<url>
http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif
</url>
</image>
<item>
<title>Conditions for Seattle, WA, US at 10:00 AM PDT</title>
<geo:lat xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">47.603561</geo:lat>
<geo:long xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">-122.329437</geo:long>
<link>
http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2490383/
</link>
<pubDate>Mon, 31 Jul 2017 10:00 AM PDT</pubDate>
<yweather:condition xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="32" date="Mon, 31 Jul 2017 10:00 AM PDT" temp="66" text="Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="32" date="31 Jul 2017" day="Mon" high="77" low="58" text="Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="32" date="01 Aug 2017" day="Tue" high="80" low="60" text="Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="32" date="02 Aug 2017" day="Wed" high="84" low="64" text="Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="32" date="03 Aug 2017" day="Thu" high="87" low="67" text="Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="04 Aug 2017" day="Fri" high="89" low="67" text="Mostly Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="05 Aug 2017" day="Sat" high="84" low="65" text="Partly Cloudy"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="06 Aug 2017" day="Sun" high="79" low="65" text="Mostly Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="07 Aug 2017" day="Mon" high="76" low="62" text="Mostly Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="08 Aug 2017" day="Tue" high="78" low="62" text="Mostly Sunny"/>
<yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="09 Aug 2017" day="Wed" high="80" low="63" text="Mostly Sunny"/>
<description>
<![CDATA[<img src="http://l.yimg.com/a/i/us/we/52/32.gif"/> <BR /> <b>Current Conditions:</b> <BR />Sunny <BR /> <BR /> <b>Forecast:</b> <BR /> Mon - Sunny. High: 77Low: 58 <BR /> Tue - Sunny. High: 80Low: 60 <BR /> Wed - Sunny. High: 84Low: 64 <BR /> Thu - Sunny. High: 87Low: 67 <BR /> Fri - Mostly Sunny. High: 89Low: 67 <BR /> <BR /> <a href="http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2490383/">Full Forecast at Yahoo! Weather</a> <BR /> <BR /> (provided by <a href="http://www.weather.com" >The Weather Channel</a>) <BR /> ]]>
</description>
<guid isPermaLink="false"/>
</item>
</channel>
</results>
</query>
    <!--  total: 5  -->
person WebDev90    schedule 28.07.2017
comment
Я получаю ту же ошибку, что и раньше, вы знаете, как найти обновленную документацию? - person Peter Smeets; 29.07.2017

Я нашел решение обновить свой старый код, и он снова работает. Я вставлю это для других людей, у которых есть проблемы с этим.

private void GetWeather()
    {
        try
        {
            String query = String.Format("https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='nederweert, lm')&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
            XmlDocument wData = new XmlDocument();
            wData.Load(query);

            XmlNamespaceManager man = new XmlNamespaceManager(wData.NameTable);
            man.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

            XmlNode channel = wData.SelectSingleNode("query").SelectSingleNode("results").SelectSingleNode("channel");
            XmlNodeList nodes = wData.SelectNodes("/query/results/channel");

            Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", man).Attributes["temp"].Value;

            Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", man).Attributes["text"].Value;

            Humidity = channel.SelectSingleNode("yweather:atmosphere", man).Attributes["humidity"].Value;

            WinSpeed = channel.SelectSingleNode("yweather:wind", man).Attributes["speed"].Value;

            Town = channel.SelectSingleNode("yweather:location", man).Attributes["city"].Value;

            TFCond = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", man).Attributes["text"].Value;

            TFHigh = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", man).Attributes["high"].Value;

            TFLow = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", man).Attributes["low"].Value;

            QEvent = "connected";
        }
        catch { QEvent = "failed"; }
    }

URL-адрес, канал XmlNode и узлы XmlNodelist изменились.

person Peter Smeets    schedule 30.07.2017