Dmitrij Kultasev
Dmitrij Kultasev

Reputation: 5745

Stream was not writable

I am trying to read response from the web SOAP Api and getting Stream was not writable error on the second run in the foreach loop. With the first value in the list ArrayList it works as expected but with the second value it says that Stream was not writable on the Stream was not writable line. What am I doing wrong?

        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");
        }

Upvotes: 1

Views: 3565

Answers (1)

naivists
naivists

Reputation: 33501

All HTTP communication happens as three steps:

  • client opens a connection
  • client sends its headers and data (in your case, the XML document) and ends the input (in your case where you close the request stream)
  • server sends its response and closes the connection

So, when you close the connection, you cannot send anything else, because you have to wait for the server answer. If you want to send more data, move the beginning of your code (where you create a new WebRequest) inside the For loop.

Upvotes: 3

Related Questions