流是不可写的

时间:2015-09-01 07:48:40

标签: c# .net streamwriter

我正在尝试从web SOAP Api读取响应并在foreach循环中第二次运行时收到Stream was not writable错误。如果list ArrayList中的第一个值按预期工作,但第二个值表示Stream was not writableStream was not writable。我做错了什么?

        WebRequest webRequest = WebRequest.Create("https://www.api.com/v2.0/xml/");
        HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
        httpRequest.Method = "POST";
        httpRequest.ContentType = "text/xml; charset=utf-8";
        httpRequest.ProtocolVersion = HttpVersion.Version11;
        httpRequest.Credentials = CredentialCache.DefaultCredentials;
        Stream requestStream = httpRequest.GetRequestStream();

        StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

        StringBuilder soapRequest;

        foreach (var bol in list) { 
        oRequest =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        oRequest = oRequest + "<file>";
        oRequest = oRequest + "<IntDocNumber>" + bol + "</IntDocNumber>";
        oRequest = oRequest + "</file>";

        soapRequest  = new StringBuilder(oRequest);
         streamWriter = new StreamWriter(requestStream, Encoding.ASCII);
        streamWriter.Write(soapRequest.ToString());
        streamWriter.Close();

        //Get the Response    
        HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
        StreamReader srd = new StreamReader(wr.GetResponseStream());
        string resulXmlFromWebService = srd.ReadToEnd();

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(resulXmlFromWebService);

        XmlNodeList xnList = xml.SelectNodes("/root/data/item");
        }

1 个答案:

答案 0 :(得分:3)

所有HTTP通信都分三步进行:

  • 客户端打开连接
  • 客户端发送其标头和数据(在您的情况下,XML文档)并结束输入(在您关闭请求流的情况下)
  • 服务器发送其响应并关闭连接

因此,当您关闭连接时,您无法发送任何其他内容,因为您必须等待服务器应答。如果要发送更多数据,请在For循环中移动代码的开头(创建新WebRequest的位置)。