title: System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically
body: <p>Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.</p>
  
  <p>Following code is here.</p>
  
  <pre><code>public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
          {
  
     String Result = String.Empty;
  
  //Specify service Url without ?wsdl suffix.
              //Reference urls for code help
              ///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
              //http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
              //String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
              String WSUrl = strURL;
  
              //Specify service name
              String WSName = ServiceName;
  
              //Specify method name to be called
              String WSMethodName = MethodToCall;
  
              //Parameters passed to the method
              String[] WSMethodArguments = Params;
              //WSMethodArguments[0] = "20500";
  
              //Create and Call Service Wrapper
              Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
  
              if (WSResults != null)
              {
                  //Decode Results
                  if (WSResults is DataSet)
                  {
                      Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
                  }
                  else if (WSResults is Boolean)
                  {   
                     bool BooleanResult = (Boolean)WSResults;
                      if(BooleanResult)
                            Result += "Result: \r\n" + "Success";
                      else
                            Result += "Result: \r\n" + "Failure";
                  }
                  else if (WSResults.GetType().IsArray)
                  {
                      Object[] oa = (Object[])WSResults;
                      //Retrieve a property value withour reflection...
                      PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
                      foreach (Object oae in oa)
                      {
                          Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
                      }
                  }
                  else
                  {
                      Result += ("Result: \r\n" + WSResults.ToString());
                  }
              }
              return Result;
          }
  
          public Object CallWebService(string webServiceAsmxUrl,
         string serviceName, string methodName, string[] args)
          {
  
              try
              {
                  System.Net.WebClient client = new System.Net.WebClient();
                  Uri objURI = new Uri(webServiceAsmxUrl);
                  //bool isProxy = client.Proxy.IsBypassed(objURI);
                  //objURI = client.Proxy.GetProxy(objURI);
                  //-Connect To the web service
                 // System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
  
                  string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
                  //string wsdlContents = client.DownloadString(ccc);
                  string wsdlContents = client.DownloadString(ccc);
                  XmlDocument wsdlDoc = new XmlDocument();
                  wsdlDoc.InnerXml = wsdlContents;
                  System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
  
                  //Read the WSDL file describing a service.
                  // System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
  
                  //Load the DOM
  
                  //--Initialize a service description importer.
                  ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                  importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
                  importer.AddServiceDescription(description, null, null);
  
                  //--Generate a proxy client. 
  
                  importer.Style = ServiceDescriptionImportStyle.Client;
                  //--Generate properties to represent primitive values.
  
                  importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
  
                  //Initialize a Code-DOM tree into which we will import the service.
                  CodeNamespace codenamespace = new CodeNamespace();
                  CodeCompileUnit codeunit = new CodeCompileUnit();
                  codeunit.Namespaces.Add(codenamespace);
  
                  //Import the service into the Code-DOM tree. 
                  //This creates proxy code that uses the service.
  
                  ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
  
                  if (warning == 0)
                  {
  
                      //--Generate the proxy code
                      CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
  
                      //--Compile the assembly proxy with the 
                      //  appropriate references
                      string[] assemblyReferences = new string[]  {
                         "System.dll", 
                         "System.Web.Services.dll", 
                         "System.Web.dll", 
                         "System.Xml.dll", 
                         "System.Data.dll"};
  
                      //--Add parameters
                      CompilerParameters parms = new CompilerParameters(assemblyReferences);
                      parms.GenerateInMemory = true; //(Thanks for this line nikolas)
                      CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
  
                      //--Check For Errors
                      if (results.Errors.Count &gt; 0)
                      {
  
                          foreach (CompilerError oops in results.Errors)
                          {
                              System.Diagnostics.Debug.WriteLine("========Compiler error============");
                              System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                          }
                          throw new Exception("Compile Error Occured calling WebService.");
                      }
  
                      //--Finally, Invoke the web service method
                      Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
                      MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
                      return mi.Invoke(wsvcClass, args);
                  }
                  else
                  {
                      return null;
                  }
              }
  
              catch (Exception ex)
              {
                  throw ex;
              }
          }
  </code></pre>
  
  <p>Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.</p>
  
  <pre><code>System.Net.WebException: The request failed with HTTP status 400: Bad Request.
   at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
  </code></pre>
  
  <p>and </p>
  
  <pre><code>System.Net.Sockets.SocketException (0x80004005): 
  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 172.17.13.7:80     
    at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)     
  
    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>