简体   繁体   English

无法将HttpWebResponse.GetResponseStream()分配给Stream

[英]Unable to assign HttpWebResponse.GetResponseStream() to Stream

I am getting jsonstream.Length threw an exception of type System.NotSupportedException error while trying for: 我正在获取jsonstream.Length尝试以下时抛出类型System.NotSupportedException错误的异常

 HttpWebRequest jsonHTTPRequest = (HttpWebRequest)WebRequest.Create(jsonRequestURL);
        jsonHTTPRequest.ContentType = "application/json; charset=utf-8";

        HttpWebResponse jsonHTTPResponse = (HttpWebResponse)jsonHTTPRequest.GetResponse();
        RootObject vikiRootObject = default(RootObject);

        using (Stream jsonstream = jsonHTTPResponse.GetResponseStream())
        {
            //encoding encode = system.text.encoding.getencoding("utf-8");
            DataContractJsonSerializer serializer =
                                     new DataContractJsonSerializer(typeof(RootObject));
            vikiRootObject = (RootObject)serializer.ReadObject(jsonstream);
        }

Also Tried with Webclient but still the same error. 也试过Webclient但仍然是同样的错误。 Is this because of large response size??? 这是因为响应大小???

The request URL is: http://www.viki.com/api/v2/channels.json 请求URL为: http//www.viki.com/api/v2/channels.json

WebClient webClient = new WebClient();
                RootObject vikiChannelData = default(RootObject);
                webClient.OpenReadAsync(new Uri(jsonRequestURL), UriKind.RelativeOrAbsolute);

                webClient.OpenReadCompleted += (obj, Args) =>
                    {
                        //DataContractJsonSerializer vikiChannelerialized = new DataContractJsonSerializer(typeof(RootObject),null);
                        DataContractJsonSerializer vikiChannelerialized = new DataContractJsonSerializer(typeof(RootObject));
                        vikiChannelData = vikiChannelerialized.ReadObject(Args.Result) as RootObject;
                        Console.WriteLine();
                    };

Edit: I tried with LINQ : 编辑:我试过LINQ:

var RootObjects = from vikiroot in vikiRootObject
                                  select new Thumbnails2
                                  {
                                      thumbnails = vikiRootObject.thumbnails
                                  };

But getting the error ,Could not find an implementation of the query pattern for source type object. 但是得到错误,无法找到源类型对象的查询模式的实现。 Select not found. 选择未找到。

My Class Structure is something like this: 我的类结构是这样的:

  public class RootObject
    {
        public int id { get; set; }
        public string title { get; set; }
        public string description { get; set; }
        public string uri { get; set; }
        public List<Episode> episodes { get; set; }
        public Thumbnails2 thumbnails { get; set; }
        public string timestamp { get; set; }
        public List<object> genres { get; set; }
        public string origin_code { get; set; }
    }

and

public class Thumbnails2
    {
        public string c_220_160 { get; set; }
        public string c_102_102 { get; set; }
        public string c_180_130 { get; set; }
        public string c_110_80 { get; set; }
        public string xl { get; set; }
        public string large { get; set; }
        public string medium { get; set; }
        public string small { get; set; }
        public string c_320_300 { get; set; }
        public string c_640_600 { get; set; }
        public string c_95_70 { get; set; }
        public string c_190_140 { get; set; }
        public string c_280_200 { get; set; }
        public string c_560_400 { get; set; }
    }

Your returned json is not a single object instead it is an array. 您返回的json不是单个对象,而是一个数组。 Since you haven't posted your RootObject and other child classes (I am too lazy to declare them) I will use Json.Net and dynamic keyword 既然你没有发布你的RootObject和其他子类(我太懒了,不能声明它们)我将使用Json.Netdynamic关键字

using (var wc = new WebClient())
{
    var json = wc.DownloadString("http://www.viki.com/api/v2/channels.json");
    dynamic dynObj = JsonConvert.DeserializeObject(json);

    foreach (var item in dynObj)
    {
        Console.WriteLine(item.title);
        foreach (var episode in item.episodes)
        {
            Console.WriteLine("\t" + episode.title);
        }
    }

}

EDIT 编辑

using (var wc = new WebClient())
{
    var json = wc.DownloadString("http://www.viki.com/api/v2/channels.json");
    var rootObj = JsonConvert.DeserializeObject<RootObject[]>(json);

    var obj = rootObj.Select(r=>new 
                    {
                        Title = r.title,
                        Thumbnail = r.thumbnails.small
                    });
}

在此输入图像描述

Did you try this? 你试过这个吗?

using (StreamReader reader = new StreamReader(jsonHTTPResponse.GetResponseStream()))
        {
             //your code goes here
        }

Actually that should be in comment, but I was unable to add one. 实际上应该是评论,但我无法添加一个。

Try doing the following by copying it into a memory stream to be able to read the Stream: 尝试通过将其复制到内存流中来执行以下操作,以便能够读取Stream:

using (Stream jsonstream = jsonHTTPResponse.GetResponseStream()) 
        { 
            DataContractJsonSerializer serializer = 
                                     new DataContractJsonSerializer(typeof(RootObject)); 

             using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonstream)))
            {
                vikiRootObject = (RootObject)serializer.ReadObject(jsonstream); 

                using (MemoryStream ms2 = new MemoryStream())
                {
                    ser.WriteObject(ms2, vikiRootObject);
                    string serializedJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0, (int)ms2.Length);
                }
            }

 } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpWebResponse.GetResponseStream转换&lt;代替&lt;etc - HttpWebResponse.GetResponseStream converts &lt; instead of < etc HttpWebResponse.GetResponseStream()(似乎是)失败,没有异常 - HttpWebResponse.GetResponseStream() (seems to be) failing with no exception HttpWebResponse.GetResponseStream():什么时候传输响应体? - HttpWebResponse.GetResponseStream(): when is the response body transmitted? 从c#中的HTTPWebResponse.GetResponseStream()上传到S3 - Upload to S3 from HTTPWebResponse.GetResponseStream() in c# HttpWebResponse.GetResponseStream()。Length引发异常,即使结果为200 OK状态 - HttpWebResponse.GetResponseStream().Length throws exception even result is 200 OK status HttpWebResponse GetResponseStream 挂在 Dispose - HttpWebResponse GetResponseStream hanging in Dispose 为什么 Stream.CanRead 在 HttpWebResponse object 上第二次调用 GetResponseStream() 时返回 false - Why does Stream.CanRead return false when calling GetResponseStream() second time on HttpWebResponse object 寻找一种方法重写HttpWebResponse的GetResponseStream方法 - Looking for a way to override the GetResponseStream Method of HttpWebResponse System.Net.HttpWebResponse.GetResponseStream()在WebException中返回截断的主体 - System.Net.HttpWebResponse.GetResponseStream() returns truncated body in WebException 使用HttpWebResponse :: GetResponseStream方法时接收不完整的数据 - Receiving incomplete data when using HttpWebResponse::GetResponseStream method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM