基本信息
源码名称:Net Core调用WebService示例Demo
源码大小:0.07M
文件格式:.zip
开发语言:C#
更新时间:2017-07-19
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍


using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.baidu.com/");
            //request.Method = "GET";
            //request.ContentType = "text/xml; charset=utf-8";
            //request.Accept = "text/html, application/xhtml xml, */*";

            //var resp = (HttpWebResponse)request.GetResponseAsync().Result;
            //StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
            //String retXml = sr.ReadToEnd();


            Hashtable ht = new Hashtable();
            ht.Add("theCityName", "北京");

            bool flag = true;
            while (flag)
            {
                Console.WriteLine("请输入1或2");
                var str = Console.ReadLine();
                if (str == "1")
                {
                    try
                    {
                        var datav1 = HttpHelper.SoapV1_1WebService("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx ", "getWeatherbyCityName", ht, "http://WebXml.com.cn/");
                        Console.WriteLine(datav1.Substring(0,10));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("v1异常了");
                    }
                }
                else if (str == "2")
                {
                    try
                    {
                        var datav2 = HttpHelper.SoapV1_2WebService("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx ", "getWeatherbyCityName", ht, "http://WebXml.com.cn/");
                        Console.WriteLine(datav2.Substring(0, 15));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("v2异常了");
                    }
                }
                else
                {
                    flag = false;
                }
            }

            //var datav2 = HttpHelper.SoapV1_2WebService("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx", "getWeatherbyCityName", ht, "http://WebXml.com.cn/");
        }
    }

    public class HttpHelper
    {
        public static string SoapV1_1WebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "text/xml; charset=utf-8";
            request.Headers["SOAPAction"] = "\""   XmlNs   (XmlNs.EndsWith("/") ? "" : "/")   MethodName   "\"";
            request.Headers["User-Agent"] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
            // 凭证
            //request.Credentials = CredentialCache.DefaultCredentials;
            //超时时间
            request.ContinueTimeout = 10000;
            byte[] data = HashtableToSoap(Pars, XmlNs, MethodName);

            Stream writer = request.GetRequestStreamAsync().Result;
            writer.Write(data, 0, data.Length);
            writer.Dispose();
            var response = (HttpWebResponse)request.GetResponseAsync().Result;
            XmlDocument doc = new XmlDocument();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Dispose();
            doc.LoadXml(retXml);
            return doc.InnerText;
        }
        private static string ObjectToSoapXml(object o)
        {
            //XmlSerializer mySerializer = new XmlSerializer(o.GetType());
            //MemoryStream ms = new MemoryStream();
            //mySerializer.Serialize(ms, o);
            //XmlDocument doc = new XmlDocument();

            //var xml = Encoding.UTF8.GetString(ms.ToArray());
            //StringBuilder sbXml = new StringBuilder();
            //sbXml.AppendLine("<?xml version=\"1.0\" encoding=\"utf - 8\"?>");
            //var tempArr = xml.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            //for (int i = 1; i <tempArr.Length; i  )
            //{
            //    sbXml.AppendLine(tempArr[i]);
            //}
            //doc.LoadXml(sbXml.ToString());

            XmlSerializer mySerializer = new XmlSerializer(o.GetType());
            MemoryStream ms = new MemoryStream();
            var streamWriter = new StreamWriter(ms, System.Text.Encoding.UTF8);
            mySerializer.Serialize(streamWriter, o);
            XmlDocument doc = new XmlDocument();

            ms.Seek(0, SeekOrigin.Begin);
            var streamReader = new StreamReader(ms, System.Text.Encoding.UTF8);
            var xml = streamReader.ReadToEnd();

            doc.LoadXml(xml);

            if (doc.DocumentElement != null)
            {
                return doc.DocumentElement.InnerXml;
            }
            else
            {
                return o.ToString();
            }
        }

        private static byte[] HashtableToSoap(Hashtable ht, String XmlNs, String MethodName)
        {
            XmlDocument doc = new XmlDocument();
            doc.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:Envelope>");
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.InsertBefore(decl, doc.DocumentElement);
            XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");

            XmlElement soapMethod = doc.CreateElement(MethodName);
            soapMethod.SetAttribute("xmlns", XmlNs);
            foreach (string k in ht.Keys)
            {

                XmlElement soapPar = doc.CreateElement(k);
                soapPar.InnerXml = ObjectToSoapXml(ht[k]);
                soapMethod.AppendChild(soapPar);
            }
            soapBody.AppendChild(soapMethod);
            doc.DocumentElement.AppendChild(soapBody);
            return Encoding.UTF8.GetBytes(doc.OuterXml);
        }


        public static string SoapV1_2WebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/soap xml; charset=utf-8";
            request.Headers["User-Agent"] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";

            // 凭证
            request.Credentials = CredentialCache.DefaultCredentials;
            //超时时间
            request.ContinueTimeout = 10000;
            byte[] data = HashtableToSoap12(Pars, XmlNs, MethodName);

            Stream writer = request.GetRequestStreamAsync().Result;
            writer.Write(data, 0, data.Length);
            writer.Dispose();
            var response = (HttpWebResponse)request.GetResponseAsync().Result;
            XmlDocument doc = new XmlDocument();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Dispose();
            doc.LoadXml(retXml);
            return doc.InnerText;
        }

        private static byte[] HashtableToSoap12(Hashtable ht, String XmlNs, String MethodName)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"></soap12:Envelope>");
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.InsertBefore(decl, doc.DocumentElement);
            XmlElement soapBody = doc.CreateElement("soap12", "Body", "http://www.w3.org/2003/05/soap-envelope");

            XmlElement soapMethod = doc.CreateElement(MethodName);
            soapMethod.SetAttribute("xmlns", XmlNs);
            foreach (string k in ht.Keys)
            {

                XmlElement soapPar = doc.CreateElement(k);
                soapPar.InnerXml = ObjectToSoapXml(ht[k]);
                soapMethod.AppendChild(soapPar);
            }
            soapBody.AppendChild(soapMethod);
            doc.DocumentElement.AppendChild(soapBody);
            return Encoding.UTF8.GetBytes(doc.OuterXml);
        }
    }
}