Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Søren Mastrup 122 posts 563 karma points c-trib
    Aug 22, 2014 @ 14:09
    Søren Mastrup
    0

    Getting JSON from an external URL

    I am trying to fetch some JSON from OpenWeatherMap, but i do not get anything returned. The URL i am trying to get JSON from is this: http://api.openweathermap.org/data/2.5/weather?lat=54.941027&lon=8.848902&units=metric&APPID=myAPIkey

    But if i use another url like umbraco.com it returns the HTML for the page.

    My code looks like this:

    var url2 = ("http://www.umbraco.com");
    var response = "";
    var requestWeather = (HttpWebRequest)WebRequest.Create(url2);
        if((@requestWeather.GetResponse().ContentLength > 0)){
            var stream = new StreamReader(requestWeather.GetResponse().GetResponseStream());
            response = stream.ReadToEnd();
            if(stream != null){
                stream.Close();
            }
        }
    

    Can any of you guys see the problem?

    Is there a smarter way of doing this? If so, how could it be done?

  • MK 429 posts 905 karma points
    Aug 22, 2014 @ 15:48
    MK
    0

     

    Hi,

    try this:

    var url = "http://api.openweathermap.org/data/2.5/weather?lat=54.941027&lon=8.848902&units=metric&APPID=myAPIkey"; 

    WebClient client = new WebClient();

    string reply = client.DownloadString(url);

    Regards,

    moshe

  • MK 429 posts 905 karma points
    Aug 22, 2014 @ 15:55
    MK
    0

    Also, if you want to have more control on your request you can use the following:

        var url = "http://api.openweathermap.org/data/2.5/weather?lat=54.941027&lon=8.848902&units=metric&APPID=myAPIkey";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

        string res = "";

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))

        {

            res = streamReader.ReadToEnd();

              }

  • Søren Mastrup 122 posts 563 karma points c-trib
    Aug 22, 2014 @ 22:27
    Søren Mastrup
    0

    Thank you Moshe! Didn't think it was that simple!

Please Sign in or register to post replies

Write your reply to:

Draft