来自Httpresponse的字符串未传递完整值

She*_*Pro 1 c# string null httpresponse

我非常需要帮助,

我正在创建一个Web请求并获取一个json字符串,Response.ContentLenth=2246但是当我在一个字符串中解析它只给出了几个100个字符时,我将其记录下来,它只获得小于964的值.字符串长度仍为2246但剩余值为只是(\0) null人物.它也Unterminated string passed in. (2246):在下一行给出错误

 FacebookFeed feed = sr.Deserialize<FacebookFeed>(data);
Run Code Online (Sandbox Code Playgroud)

如果响应流包含小于964个字符的字符,它可以正常工作.

以下是最后一行遇到的完整代码错误的摘录.

    System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();
    System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(@"https://graph.facebook.com/100000570310973_181080451920964");
    req.Method = "GET";
    System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();

    byte[] resp = new byte[(int)res.ContentLength];
    res.GetResponseStream().Read(resp, 0, (int)res.ContentLength);
    string data = Encoding.UTF8.GetString(resp);
    FacebookFeed feed = sr.Deserialize<FacebookFeed>(data);
Run Code Online (Sandbox Code Playgroud)

给出的错误是

Unterminated string passed in. (2246): {"id":"100000570310973_1810804519209........ (with rest of data in the string data including null chars)
Run Code Online (Sandbox Code Playgroud)

以下是我的代码中使用的类的形状:

public class FacebookFeed
{
    public string id { get; set; }
    public NameIdPair from { get; set; }
    public NameIdPair to { get; set; }
    public string message { get; set; }
    public Uri link{get;set;}
    public string name{get; set;}
    public string caption { get; set; }
    public Uri icon { get; set; }
    public NameLinkPair[] actions { get; set; }
    public string type { get; set; }
    public NameIdPair application { get; set; } //Mentioned in Graph API as attribution
    public DateTime created_time { get; set; }
    public DateTime updated_time { get; set; }
    public FacebookPostLikes likes { get; set; }
}

public class NameIdPair
{
    public string name { get; set; }
    public string id { get; set; }
}

public class NameLinkPair
{
    public string name { get; set; }
    public Uri link{get; set;}
}

public class FacebookPostLikes
{
    public NameIdPair[] data { get; set; }
    public int count { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*kXA 7

您假设res.GetResponseStream().Read将一次性返回整个响应.实际上,Stream.Read()返回读取的字节数 - 如果这小于您期望的数字,则需要一直调用它,直到获取了所有响应块.您可以在http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx上的示例中看到这一点.