简体   繁体   中英

How to call API URL in asp.net

I am new to asp.net. I want to call api url and the response will be return in terms of xml. My Question is how to call below api url in my asp.net code with c#.

I am using vs 2008 with 3.5.

API URL: http://free.worldweatheronline.com/feed/weather.ashx?q=Mumbai&format=xml&num_of_days=2&key=apikey

Can any one help me.

How the following code works? And more APIs to implement this, I think this is the easiest one.

    WebClient webClient = new WebClient();
    string content = webClient.DownloadString("http://free.worldweatheronline.com/feed/weather.ashx?q=Mumbai&format=xml&num_of_days=2&key=api_key");
    XElement xml = XElement.Parse(content);
    using (MemoryStream ms = new MemoryStream())
    {
        xml.Save(ms);
        // use the ms here.
    }

Or just use this to get the MemoryStream.

MemoryStream ms = new MemoryStream(webClient.DownloadData(uri));
    //Load XML (replace "apikey" in the query string by your API key)
    XDocument xdoc = XDocument.Load(@"http://free.worldweatheronline.com/feed/weather.ashx?q=Mumbai&format=xml&num_of_days=2&key=apikey");

    //Run query with LINQ
        var query = from cc in xdoc.Descendants("current_condition")
                   select cc;

    //To convert memory stream .NET 3.5
    MemoryStream ms = new MemoryStream();
    XmlWriterSettings xws = new XmlWriterSettings();
    xws.OmitXmlDeclaration = true;
    xws.Indent = true;

    using (XmlWriter xw = XmlWriter.Create(ms, xws))
    {
        xdoc.WriteTo(xw);
    }

    // to convert Memory stream if you are using .NET 4+
   Stream stream = new MemoryStream();
   xdoc.Save(stream);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM