2013-10-09 60 views
2

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

以下是错误:

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

我要打电话到服务并解析其中的数据,什么是做到这一点的simpliest方式?

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

        } 
       } 

      } 
     } 
    } 

回答

4

我跑我的机器上的代码见herehere,它执行得很好,我能够遍历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的。使用起来更容易。

+0

能否请您加入,帮助您查看响应数据 –

+0

我已经更新了我的代码的答案代码。 –

3

如果你运行的.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(); 

完整例子

+0

当我尝试用你的代码在控制台应用程序我得到了HTTP错误:“HttpClient的”找不到(是否缺少using指令或。我正在使用.NET 4.55组件,我应该做的避免这种错误 –

+1

有安装Web API客户端库按照本指南:??http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-一个网客户端 – qujck

+1

错字:_client,而不是客户端匹配声明的名称 –