title: Getting “Unable to connect to a remote server” error while calling a service from Web Application
body: <p>I am getting "Unable to connect to a remote server" error while calling a service using Web Application. But the same code runs when I call it from a console application. I just have the URL of the service. </p>
  
  <p>Here is the stack trace:</p>
  
  <pre><code>at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, 
      SocketAddress socketAddress) 
  at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) 
  at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, 
      Socket s4, Socket s6, Socket&amp; socket, IPAddress&amp; address, 
      ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, 
      Exception&amp; exception) 
  </code></pre>
  
  <p>Here is the code which I am using:</p>
  
  <pre><code>    HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; 
      req.Method = "POST"; 
      req.ContentType = "application/x-www-form-urlencoded"; 
                  X509Certificate cert = X509Certificate.CreateFromCertFile(certificatePath); 
      req.ClientCertificates.Add(cert); 
  
  
    using (StreamReader sr = File.OpenText(inFilePath))   
  
    { 
          string xml = sr.ReadToEnd(); 
          string postRaw = string.Format("request={0}", System.Web.HttpUtility.UrlEncode(xml)); 
          byte[] buf = Encoding.UTF8.GetBytes(postRaw); 
  
          req.ContentLength = buf.Length; 
          try 
          { 
              Stream s = req.GetRequestStream(); //This is where I get the error. 
  
  
              s.Write(buf, 0, buf.Length); 
              s.Close(); 
          } 
          catch (Exception ex) 
          { 
          } 
      } 
  
      HttpWebResponse resp = req.GetResponse() as HttpWebResponse; 
  
  
      if (resp.StatusCode == HttpStatusCode.OK) 
      { 
          StringBuilder sb = new StringBuilder(); 
  
          using (StreamReader reader = new StreamReader(resp.GetResponseStream(),     System.Text.Encoding.UTF8)) 
          { 
              string line; 
              while ((line = reader.ReadLine()) != null) 
              { 
                  sb.Append(line + "\r\n"); 
              } 
          } 
  
          string resXml = sb.ToString(); 
      } 
  </code></pre>
  
  <p>Is there any setting in web.config or on IIS which I need to mention for this to work in a web application?</p>
  
  <p>One of my team member has already asked this question but no one has replied to it as yet. So that's why I'm posting it again.</p>
  
  <p>This is the exact inner exception:</p>
  
  <blockquote>
    <p>A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond  XX.XX.XXX.XXX:443</p>
  </blockquote>