我目前工作的一個簡單的應用程序,利用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