Malik
Malik

Reputation: 114

Yahoo Weather API using Oauth

I am stuck on implementing the Yahoo Weather private API call. This is my code snippet, whenever I call it using valid clientId & Secret it returns 401 (unauthorized).

var outhWc = new WebClient();
outhWc.Credentials = new NetworkCredential(clientId, clientSecret);
outhWc.Headers.Add(HttpRequestHeader.Accept, "application/json");
var outhresponse = outhWc.DownloadData("https://query.yahooapis.com/v1/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json");

It always throws an exception. I also try to pass username and password in NetworkCredentials and also try to pass clientId and Secret in Header but I cannot find a successful call.

Upvotes: 2

Views: 1425

Answers (1)

Martín
Martín

Reputation: 11

So I've been stuck with the same issue here. Finally I implemented the following code, based on the oAuth c# simple class found at http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs

   public void LoadWeather() {
        string URLDes, Params = "";
        string Signature, BaseURL, cKey, cSecret = "";

        OAuthBase oAuth = new OAuthBase();
        BaseURL = "http://weather.yahooapis.com/forecastrss?w=" + textBox1.Text + "&u=f";
        cKey = "YOUR API KEY";
        cSecret = "YOUR API SECRET";

        Signature = oAuth.GenerateSignature(new Uri(BaseURL), cKey, cSecret, "", "", "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out URLDes, out Params);

        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += HttpsCompleted;
        wc.DownloadStringAsync(new Uri(String.Format("{0}?{1}&oauth_signature={2}", URLDes, Params, Signature)));
    }

    private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) {
        if (e.Error == null) {
            XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
            xdoc.Save("c:\\weather.xml");
            richTextBox1.Text = xdoc.FirstNode.ToString();
        } else {
            richTextBox1.Text = e.Error.Message;
        }
    }

As you can see, I already have the city ID. This sample downloads the xml string returned by the API. Worked for me, hope it helps!

Upvotes: 1

Related Questions