开发者

getting XML from other domain using ASP.NET

I'm fairly new to ASP.NET. And I was wondering how I could go about getting xml from a site (Kuler's API in this case), and then post the result using AJAX?

So what I want here, is 开发者_StackOverflow社区to be able to do a query to Kuler's API. The URL would be something like "http://kuler-api.adobe.com/rss/search.cfm?query="+queryVariable

Then send the resulting xml back to JS in some way.

Any pointers would be appreciated (:


What you'll need to do is have a handler that will perform the request for the XML and send it back to the browser using AJAX. It will act as an intermediary between server and client, and you won't have to worry about cross-domain policies.

This is what I do on one of my sites. I have a handler (let's call it proxy.ashx) that I call from a jQuery AJAX request. The proxy.ashx simply performs a WebClient.DownloadString action on the remote URL and sends the remote response (the XML) back to the client-side.


I think that Tim said enough, but what I would like to add is how you could do the server side request:

            XmlDocument doc = new XmlDocument();
            HttpWebRequest r = (HttpWebRequest)HttpWebRequest.Create("http://kuler-api.adobe.com/rss/search.cfm?query="+queryVariable);
            r.Method = "POST";


            using (Stream writeStream = r.GetRequestStream())
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] bytes = encoding.GetBytes(bodyRequest);
                writeStream.Write(bytes, 0, bytes.Length);
            }
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)r.GetResponse())
                {

                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            doc.Load(readStream);
                        }
                    }

                }
            }
            catch (WebException ex)
            {
                //Handle exception
            }


I'd do the whole thing in Javascript using Jquery's ajax library, if possible. It's very simple to use and you don't have to worry about getting the XML from server to client that way.


Write a .net webservice (.asmx) that encapsulate the cross domain call, then call that service with AJAX.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜