0

将 json 内容写入流写入器后,我在关闭流写入器时出错。以下是我正在使用的代码。找不到什么问题。它正在写入 REST 服务。

WebRequest request = WebRequest.Create(String.Format("{0}/EventLog", restPath));
            request.ContentType = "application/json";
            request.Method = "POST";
            request.ContentLength = jsonstring.Length;                
            System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
            sw.Write(jsonstring);                
            sw.Close();
            sw.Dispose();
            HttpWebResponse res = (HttpWebResponse)request.GetResponse();

例外:“在写入所有字节之前无法关闭流。”

4

1 回答 1

1

确保request.ContentLength真的等于内容长度(以字节为单位)。

这会引发相同的错误:

string data = "mydata";

WebRequest request = WebRequest.Create("http://google.de/");
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = data.Length + 1;
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
sw.Dispose();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
于 2012-06-07T09:40:41.953 回答