2011-03-21 52 views
1

我有以下代码:流不可读 - 没有处理,为什么这不起作用?

// Create POST data and convert it to a byte array. 
string postData = "name=t&description=tt"; 
byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
// Set the ContentType property of the WebRequest. 
request.ContentType = "application/x-www-form-urlencoded"; 
// Set the ContentLength property of the WebRequest. 
request.ContentLength = byteArray.Length; 
// Get the request stream. 
using (StreamReader reader = new StreamReader(request.GetRequestStream())) 
{ 
    string s = reader.ReadToEnd(); 
} 

当流量击中使用(.....)语句,我得到以下异常:

流未读

我想将整个请求流读入一个字符串,没有任何东西被关闭,所以代码应该工作?

+0

什么是'request'?你在哪里设定内容? – Cameron 2011-03-21 23:52:29

+0

您不应该试图写入流吗? – 2011-03-21 23:54:46

+0

类似的情况已得到解答,并可能有所帮助,请参阅:http://stackoverflow.com/a/43981770/2791237 – 2017-05-15 14:19:09

回答

3

您写入请求流并从响应流中读取。

string postData = "name=t&description=tt"; 
    byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
    // Set the ContentType property of the WebRequest. 
    request.ContentType = "application/x-www-form-urlencoded"; 
    // Set the ContentLength property of the WebRequest. 
    request.ContentLength = byteArray.Length; 
    // Get the request stream. 

    var stream = request.GetRequestStream(); 
    stream.Write(byteArray, 0, byteArray.Length); 
+0

感谢。但是,我能看不到正在发送的请求的xml正文吗? – dotnetdev 2011-03-22 00:05:07

+0

@dotnetdev - 可能在调试器中。无论如何,它不是XML,它只是你指定的字符串,URL编码,所以你已经有了内容。 – tvanfosson 2011-03-22 00:09:28

+0

@dotnetdev - 如果你绝对不需要你,可以从HttpWebRequest派生自己的请求类并重写GetRequestStream,以便它返回包含过滤器的基础流。您可以让过滤器将实际的请求存储到流中,并通过您的课程中的其他属性提供给您。 – tvanfosson 2011-03-22 00:16:27