我目前工作的一个简单的应用程序,利用JSON对象发布到API,并得到响应数据时。然而,当我运行POST方法,该POST的响应是如此之大,我遇到OutOfMemory例外。C#OutOfMemory例外阅读投递响应
我目前使用的WebClient和过程中的CookieContainer:
string jsonObject ="...."; //Example JSON string - It's very small
using (var client = new WebClient())
{
var auth = new NameValueCollection();
values["username"] = "username";
values["password"] = "password";
client.uploadValues(endpoint,auth);
// This is causing the OutOfMemory Exception
var response = client.uploadString(endpoint, jsonObject);
}
我特地到这个问题,并已设置属性AllowStreamBuffering是假的。
client.AllowStreamBuffering() = false;
但是,我仍然遇到问题,并不知道如何控制POST响应。
更新:2017年7月5日
感谢@Tim的建议,我已经搬到了响应流,但我现在遇到有关的实际响应的问题。用POST方法写JSON(作为一个字符串)到终点后,脚本被卡住在尝试读取响应。
String endPoint = @"http://example.com/v1/api/";
String json = @"....";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "POST";
request.KeepAlive = false;
request.AllowReadStreamBuffering = false;
/* Pretend this middle part does the Authorization with username and password. */
/* I have actually authenticated using the above method, and passed a key to the request */
//This part POST the JSON to the API
using (StreamWriter writeStream = new StreamWriter(request.GetRequestStream()))
{
writeStream.Write(json);
writeStream.Flush();
writeStream.Close();
}
//This bottom part opens up a console, but never reads or loads the data
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
我想知道如果JSON不是可能编码。
(边注:我已经看过书面响应,一行行到一个文件,但它是导致问题的答复 - http://cc.davelozinski.com/c-sharp/fastest-way-to-read-text-files)
这里的答案似乎与您的问题有关:https://stackoverflow.com/questions/15163451/system-outofmemoryexception-was-thrown-webclient-downloadstringasynch – Tim
嗨蒂姆,感谢您的信息。我还没有尝试使用HttpWebRequest来获取getResponse(),但如果它是解决方案,我会在这里更新它。 –
你可能需要使用一个流,BeginGetResponse应该让你抓住整个响应块 – Tim