从C#调用OData服务

时间:2013-10-09 06:30:14

标签: c# wcf rest odata

我使用下面的代码从C#调用OData服务(来自Odata.org的工作服务),我没有得到任何结果。
错误在于response.GetResponseStream()

这是错误:

Length = 'stream.Length' threw an exception of type 'System.NotSupportedException'

我想调用该服务并从中解析数据,最简单的方法是什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;

namespace ConsoleApplication1
    {
    public class Class1
        {

        static void Main(string[] args)
            {
            Class1.CreateObject();
            }
        private const string URL = "http://services.odata.org/OData/OData.svc/Products?$format=atom";


        private static void CreateObject()
            {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "GET";

            request.ContentType = "application/xml";
            request.Accept = "application/xml";
            using (WebResponse response = request.GetResponse())
                {
                using (Stream stream = response.GetResponseStream())
                    {

                    XmlTextReader reader = new XmlTextReader(stream);

                    }
                }

            }
        }
    }

2 个答案:

答案 0 :(得分:5)

如果您运行的是.NET 4.5,请查看HttpClientMSDN

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(endpoint);
Stream stream = await response
    .Content.ReadAsStreamAsync().ConfigureAwait(false);
response.EnsureSuccessStatusCode();

有关完整示例,请参阅herehere

答案 1 :(得分:5)

我在我的机器上运行了你的代码,它执行得很好,我能够遍历由XmlTextReader检索的所有XML元素。

    var request = (HttpWebRequest)WebRequest.Create(URL);
    request.Method = "GET";

    request.ContentType = "application/xml";
    request.Accept = "application/xml";
    using (var response = request.GetResponse())
    {
        using (var stream = response.GetResponseStream())
        {
            var reader = new XmlTextReader(stream);
            while (reader.Read())
            {
                Console.WriteLine(reader.Value);
            }
        }
    }

但正如@qujck建议的那样,看看HttpClient。它更容易使用。