title: HttpWebRequest.GetRequestStream() Timeout
body: <p>I have a service that builds an HttpWebRequest and sets its body with a JSON string to be sent to a system's API. At the point of calling for the request stream, I am ocassionaly getting a WebException timeout error. Why would it error at this point? Does it test connecting to the other system before continuing?</p>
  
  <pre><code>try
  {
      //Get default request data
      if (requestObj == null)
          requestObj = new ApiRequest();
  
      //Convert request info to json+bytes
      string url = _baseUrl + path;
      string requestStr = JsonConvert.SerializeObject(requestObj, _jsonSettings);
      requestObjJson = requestStr;
  
      byte[] data = Encoding.UTF8.GetBytes(requestStr);
  
      //Post to SystemX
      webRequest = (HttpWebRequest)WebRequest.Create(url);
      webRequest.ContentType = "application/json;charset=UTF-8";
      webRequest.Headers.Add("access_token", _accessToken);
      webRequest.Method = "POST";
      webRequest.ContentLength = data.Length;
  
      webRequestJson = JsonConvert.SerializeObject(webRequest, Formatting.Indented);
  
      using (Stream dataStream = webRequest.GetRequestStream())
      {
          dataStream.Write(data, 0, data.Length);
          dataStream.Close();
      }
  
      webRequestJson = JsonConvert.SerializeObject(webRequest, Formatting.Indented);
  
      LogMessage("SystemXApiAdapter._request() Request", "Information only. Not an error.", webRequestJson + ";" + requestObjJson, connectionString, customerName, licenseInfoID);
  
      //Get response
      string responseString = null;
      HttpStatusCode status;
      using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
      {
          if (response != null)
          {
              using (Stream stream = response.GetResponseStream())
              using (StreamReader sr = new StreamReader(stream))
              {
                  responseString = sr.ReadToEnd();
                  status = response.StatusCode;
              }
  
              response.Close();
          }
          else
          {
              status = HttpStatusCode.NoContent;
          }
      }
      T responseObj = null;
  
      LogMessage("SystemXApiAdapter._request() Response", "Information only. Not an error.", responseString, connectionString, customerName, licenseInfoID);
  
      if (typeof(T) == typeof(EmptyApiResponse))
          return null;
  
      if (string.IsNullOrEmpty(responseString))
          throw new Exception("Empty response for non-empty request");
  
      responseObj = JsonConvert.DeserializeObject&lt;T&gt;(responseString);
  
      if (callback != null)
          callback(responseObj);
  
      //Get next page of data if needed
      if (handlePaging &amp;&amp; status == HttpStatusCode.PartialContent)
      {
          //Move to next page and recursively make more requests until we've got everything
          requestObj.page_num++;
          T moreData = _request&lt;T&gt;(path, connectionString, customerName, licenseInfoID, true, requestObj, callback);
          if (moreData != null)
              responseObj = (T)(responseObj).AppendResponseData(moreData);
      }
  
      return responseObj;
  }
  catch (Exception ex)
  {
      SystemXApiException SystemXEx = new SystemXApiException(requestObj, ex, webRequestJson);
  
      if (!bIsRetry &amp;&amp; SystemXEx.StatusCode.HasValue &amp;&amp; retryOnStatuses.Contains(SystemXEx.StatusCode.Value))
      {
          return _request&lt;T&gt;(path, connectionString, customerName, licenseInfoID, handlePaging, requestObj, callback, true);
      }
      else
      { 
          throw SystemXEx;
      }
  
      if (ex is WebException)
      {
          WebException webEx = (WebException)ex;
          HttpStatusCode? StatusCode = null;
          string responseBody = null;
  
          //Read Status Code
          if (webEx.Status == WebExceptionStatus.ProtocolError)
          {
              var response = webEx.Response as HttpWebResponse;
              if (response != null)
              {
                  StatusCode = response.StatusCode;
              }
          }
  
          //Retry once on applicable status code
          if (!bIsRetry &amp;&amp; StatusCode.HasValue &amp;&amp; retryOnStatuses.Contains(StatusCode.Value))
              return _request&lt;T&gt;(path, connectionString, customerName, licenseInfoID, handlePaging, requestObj, callback, true);
  
          //Read response Body
          if (webEx.Response != null)
          {
              using (Stream responseStream = webEx.Response.GetResponseStream())
              using (StreamReader sr = new StreamReader(responseStream, Encoding.Default))
              {
                  responseBody = sr.ReadToEnd();
              }
          }
          else
          {
              responseBody = "Empty response body.";
          }
  
          string message = null;
  
          //Format new Exception
          if (StatusCode.HasValue)
              message = string.Format("{0} {1}: {2}: {3}: {4}", (int)StatusCode, StatusCode.ToString(), responseBody, requestObjJson, webRequestJson);
          else
              message = string.Format("{0} {1}: {2}: {3}: {4}", "No status code", "No status code", responseBody, requestObjJson, webRequestJson);
  
          throw new Exception(message, ex);
      }
      else
          throw;
  }
  finally
  {
      if (webRequest != null)
      {
          webRequest.Abort();
      }
  }
  </code></pre>