title: How do I handle/fix "Error getting response stream (ReadDone2): ReceiveFailure" when using MonoTouch?
body: <p>I am using MonoTouch to build an iPhone app.  In the app I am making Web Requests to pull back information from the web services running on our server.</p>
  
  <p>This is my method to build the request:</p>
  
  <pre><code>public static HttpWebRequest CreateRequest(string serviceUrl, string methodName, JsonObject methodArgs)
  {
      string body = "";
  
      body = methodArgs.ToString();
  
      HttpWebRequest request = WebRequest.Create(serviceUrl) as HttpWebRequest;
  
      request.ContentLength = body.Length; // Set type to POST
      request.Method = "POST";
      request.ContentType = "text/json";
      request.Headers.Add("X-JSON-RPC", methodName);
  
      StreamWriter strm = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
      strm.Write(body);
      strm.Close();
  
      return request;
  }
  </code></pre>
  
  <p>Then I call it like this:</p>
  
  <pre><code>var request = CreateRequest(URL, METHOD_NAME, args);
  request.BeginGetResponse (new AsyncCallback(ProcessResponse), request);
  </code></pre>
  
  <p>And ProcessResponse looks like this:</p>
  
  <pre><code>private void ProcessResponse(IAsyncResult result)
  {
  
      try 
      {
           HttpWebRequest request = (HttpWebRequest)result.AsyncState;
  
           using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result)) // this is where the exception gets thrown
           {
               using (StreamReader strm = new System.IO.StreamReader(response.GetResponseStream()))
               {
                   JsonValue value = JsonObject.Load(strm);
  
                   // do stuff...
  
                   strm.Close();
               } // using
               response.Close();
           } // using
  
           Busy = false;
       }
       catch(Exception e)
       {
           Console.Error.WriteLine (e.Message);
       }
  }
  </code></pre>
  
  <p>There is another question about this issue for Monodroid and the answer there suggested explicitly closing the output stream.  I tried this but it doesn't solve the problem.  I am still getting a lot of ReadDone2 errors occurring. </p>
  
  <p>My workaround at the moment involves just re-submitting the Web Request if an error occurs and the second attempt seems to work in most cases.  These errors only happen when I am testing on the phone itself and never occur when using the Simulator.</p>