How to call a web service with no wsdl in .net

后端 未结 5 575
旧巷少年郎
旧巷少年郎 2020-12-08 04:53

I have to connect to a third party web service that provides no wsdl nor asmx. The url of the service is just http://server/service.soap

I have read this article ab

5条回答
  •  忘掉有多难
    2020-12-08 05:43

    Well, I finally got this to work, so I'll write here the code I'm using. (Remember, .Net 2.0, and no wsdl to get from web service).

    First, we create an HttpWebRequest:

    public static HttpWebRequest CreateWebRequest(string url)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Headers.Add("SOAP:Action");
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";
        return webRequest;
    }
    

    Next, we make a call to the webservice, passing along all values needed. As I'm reading the soap envelope from a xml document, I'll handle the data as a StringDictionary. Should be a better way to do this, but I'll think about this later:

    public static XmlDocument ServiceCall(string url, int service, StringDictionary data)
    {
        HttpWebRequest request = CreateWebRequest(url);
    
        XmlDocument soapEnvelopeXml = GetSoapXml(service, data);
    
        using (Stream stream = request.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }
    
        IAsyncResult asyncResult = request.BeginGetResponse(null, null);
    
        asyncResult.AsyncWaitHandle.WaitOne();
    
        string soapResult;
        using (WebResponse webResponse = request.EndGetResponse(asyncResult))
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }
    
        File.WriteAllText(HttpContext.Current.Server.MapPath("/servicios/" + DateTime.Now.Ticks.ToString() + "assor_r" + service.ToString() + ".xml"), soapResult);
    
        XmlDocument resp = new XmlDocument();
    
        resp.LoadXml(soapResult);
    
        return resp;
    }
    

    So, that's all. If anybody thinks that GetSoapXml must be added to the answer, I'll write it down.

提交回复
热议问题