2017-07-25 54 views
1

我正在尝试将SOAP消息发送到外部Url。 我的代码如下。如何将SOAP消息提交到外部Web服务URL?

namespace SeadSOAPMessage 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      CallWebService(); 
      Console.ReadLine(); 
     } 


     public static void CallWebService() 
     { 
      var _url = "http://www.webservicex.com/globalweather.asmx"; 
      var _action = "http://www.webservicex.com/globalweather.asmx?op=GetWeather"; 


      XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); 
      HttpWebRequest webRequest = CreateWebRequest(_url, _action); 
      InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); 

      // begin async call to web request. 
      IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); 

      // suspend this thread until call is complete. You might want to 
      // do something usefull here like update your UI. 
      asyncResult.AsyncWaitHandle.WaitOne(); 

      // get the response from the completed web request. 
      string soapResult; 
      using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) 
      { 
       using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) 
       { 
        soapResult = rd.ReadToEnd(); 
       } 
       Console.Write(soapResult); 
      } 
     } 

     private static HttpWebRequest CreateWebRequest(string url, string action) 
     { 
      HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 
      webRequest.Headers.Add("SOAPAction", action); 
      webRequest.ContentType = "text/xml;charset=\"utf-8\""; 
      webRequest.Accept = "text/xml"; 
      webRequest.Method = "POST"; 
      return webRequest; 
     } 

     private static XmlDocument CreateSoapEnvelope() 
     { 
      XmlDocument soapEnvelop = new XmlDocument(); 
      soapEnvelop.LoadXml(@"<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""><soap:Body><GetWeather xmlns=""http://www.webserviceX.NET""><CityName>string</CityName><CountryName>string</CountryName></GetWeather></soap:Body></soap:Envelope>"); 
      return soapEnvelop; 
     } 

     private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) 
     { 
      using (Stream stream = webRequest.GetRequestStream()) 
      { 
       soapEnvelopeXml.Save(stream); 
      } 
     } 
    } 
} 

正在使用的WSDL是。 wsdl url

method Url 在这里做所有的Proceess我收到异常,因为

The remote server returned an error: (500) Internal Server Error. 

而且如果我将继续执行,然后第二次后,我收到另一个exceptioni.e

EndGetResponse can only be called once for each asynchronous operation. 

那么,我做错了什么?

+0

尝试追查例如像代理请求小提琴手,看看是否有任何额外的信息在回复中。 – stuartd

回答

0

通过传递正确的URL的int变量_action即

var _action = "http://www.webservicex.com/globalweather.asmx/GetWeather"; 

解决了这一问题,并传递错误的一个即

var _action = "http://www.webservicex.com/globalweather.asmx?op=GetWeather"; 
相关问题