嗨,我非常需要这里的帮助,
我正在发出Web请求,并使用Response.ContentLenth=2246
获取json字符串,但是当我将其解析为一个字符串时,它仅给出100个字符,我对其进行追踪,发现它仅获得小于964的值。字符串长度仍为2246,但其余值只是(\0)
null
个字符。在下一行也给出错误Unterminated string passed in. (2246):
FacebookFeed feed = sr.Deserialize<FacebookFeed>(data);
如果响应流中的字符数少于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);
给出的错误是
Unterminated string passed in. (2246): {"id":"100000570310973_1810804519209........ (with rest of data in the string data including null chars)
以下是我的代码中使用的类的形状:
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; }
}
最佳答案
您假设res.GetResponseStream().Read
将一次性返回整个响应。实际上,Stream.Read()
返回已读取的字节数-如果该数目小于您期望的数目,则需要继续调用它,直到获取所有响应块为止。您可以在http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx的示例中看到这一点。
关于c# - 来自Httpresponse的字符串未传递完整值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539453/