从C#调用OData服务

Jea*_*hhe 3 c# rest wcf odata

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

这是错误:

Length = 'stream.Length' threw an exception of type 'System.NotSupportedException'
Run Code Online (Sandbox Code Playgroud)

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

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);

                    }
                }

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

quj*_*jck 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();
Run Code Online (Sandbox Code Playgroud)

请参见此处此处以获取完整示例


Vag*_*lov 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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是正如@qujck所建议的,请看一下HttpClient。它更容易使用。