C# 调用 WebServices Api接口 WSDL 通过WebResponse 请求

https://www.cnblogs.com/Sheldon180621/p/14498646.html

 

 

 

方法一、引用*.wsdl文件

WebService服务端会提供wsdl文件,客户端通过该文件生成.cs文件以及生成.dll

PS:注意若是服务端只提供了URL,那可以通过在URL后面加上“?wsdl”在浏览器上访问,复制页面的代码内容,粘贴到文本文件,将文件后缀改为“wsdl”,即可得到wsdl文件。

通过URL或wsdl文件都可生成.cs文件。

生成.cs文件的方法有以下两种:

1):通过VS命令行工具生成

 

 

1.1在打开的命令行工具中输入命令“wsdl/language:c# /n:CHEER.PresentationLayer /out:生成的物理路径(需先创建一个空的cs文件)WebService接口URL  

1.2在打开的命令行工具中输入命令“wsdl/language:c# /n:CHEER.PresentationLayer /out:生成的物理路径(需先创建一个空的cs文件)wsdl文件物理路径”                                                                                                                                                                                                                                                                                                                                                                                                                                                         

PS:在导入文件时,要注意是否原wsdl文件中有多余语句

2):VS中添加外部工具(方便以后使用)

VS工具菜单->外部工具->如下图

 

 

 

 输入上图红框中的各个参数,其中,命令框中输入:C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\wsdl.exe,即wsdl.exe的物理路径。

初始目录:$(ItemDir)表示当前目录下。

命名空间使用时直接改成自定义的名称即可。

下图是该外部工具的使用,先自定义命名空间名称,再在out:后面加上空格,再加上WebService的URL或wsdl文件物理路径。

 

 

 

方法二、已知WebService接口的URL,直接调用

 在VS中,添加服务引用--高级--添加web引用,直接输入webservice URL

然后直接实例化该命名空间下的类的对象,调用该接口下的各个方法即可。

 

方法三、动态调用WebService

先创建帮助类

复制代码
 1  /// <summary>
 2     /// 动态调用WebService的帮助类
 3     /// </summary>
 4    public class WebServiceHelper
 5     {
 6         #region InvokeWebService
 7         ///<summary>
 8         ///动态调用web服务
 9         /// </summary>
10         /// <param name="url">WSDL服务地址</param>
11         /// <param name="methodname">方法名</param>
12         /// <returns></returns>
13         
14         public object InvokeWebService(string url,string methodname,object[] args)
15         {
16             return this.InvokeWebService(url, null, methodname, args);
17         }
18 
19         ///<summary>
20         ///动态调用web服务
21         ///</summary>
22         ///<param name="url">WSDL服务地址</param>
23         ///<param name="classname">类名</param>
24         ///<param name="methodname">方法名</param>
25         ///<param name="args">参数</param>
26         ///<returns></returns>
27         
28         public object InvokeWebService(string url,string classname,string methodname,object[] args)
29         {
30             string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
31             if((classname == null )||(classname ==""))
32             {
33                 classname = WebServiceHelper.GetWsClassName(url);
34             }
35             try
36             {
37                 //获取WSDL
38                 WebClient wc = new WebClient();
39                 if (!url.ToUpper().Contains("WSDL"))
40                 {
41                     url = string.Format("{0}?{1}",url,"WSDL");
42                 }
43                 Stream stream = wc.OpenRead(url);
44                 ServiceDescription sd = ServiceDescription.Read(stream);
45                 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
46                 sdi.AddServiceDescription(sd, "", "");
47                 CodeNamespace cn = new CodeNamespace(@namespace);
48                 //生成客户端代理类代码
49                 CodeCompileUnit ccu = new CodeCompileUnit();
50                 ccu.Namesapces.Add(cn);
51                 sdi.Import(cn, ccu);
52                 CSharpCodeProvider icc = new CSharpCodeProvider();
53                 //设定编译参数
54                 CompilerParameters cplist = new CompilerParameters();
55                 cplist.GenerateExecutable = false;
56                 cplist.GenerateInMemory = true;
57                 cplist.ReferenceAssemblies.Add("System.dll");
58                 cplist.ReferenceAssemblies.Add("System.XML.dll");
59                 cplist.ReferenceAssemblies.Add("System.Web.Services.dll");
60                 cplist.ReferenceAssemblies.Add("System.Data.dll");
61                 //编译代理类
62                 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
63                 if(true == cr.Errors.HasErrors)
64                 {
65                     StringBuilder sb = new StringBuilder();
66                     foreach(CompilerError ce in cr.Errors)
67                     {
68                         sb.Append(ce.ToString());
69                         sb.Append(Environment.NewLine);
70                     }
71                     throw new Exception(sb.ToString());
72                 }
73                 //生成代理实例,并调用方法
74                 System.Reflection.Assembly assembly = cr.CompiledAssembly;
75                 Type t = assembly.GetType(@namespace + "." + classname, true, true);
76                 object obj = Activator.CreateInstance(t);
77                 System.Reflection.MethodInfo mi = t.GetMethod(methodname);
78                 return mi.Invoke(obj, args);
79             }
80             catch(Exception ex)
81             {
82                 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
83             }
84         }
85         private static string GetWsClassName(string wsUrl)
86         {
87             string[] parts = wsUrl.Split('/');
88             string[] pps = parts[parts.Length - 1].Split('.');
89             if (pps[0].Contains("?"))
90             {
91                 return pps[0].Split('?')[0];
92             }
93             return pps[0];
94         }
95         #endregion
96     }
复制代码

然后调用,如下

WebServiceHelper webService =new WebServiceHelper();
object obj =wenService.InvokeWebService("需要引用的URL","Add",new object[]{22,33});
DataTable dt =obj as DataTable;

PS:此方法比较麻烦,每次调用InvokeWebService都是在内存中创建动态程序集,效率较低。

以上内容就是C#的三种调用WebService接口方法的详细内容了。

 

这些方法试了一下都是不行的,具体问题出在哪里没有找到,我已没有时间研究了,希望以后能有人能写出来一个调用WebService的帮助类出来吧,

而不是使用Visual Studio 自动生成的调用服务类,下面是 dotNet 的 dotNET Framework 也是差不多的

 

 

https://blog.csdn.net/weixin_43671185/article/details/103157774

.NetCore引用webservice方法

.NetCore引用webservice方法
一、引入服務 在这里插入图片描述

在这里插入图片描述
複製webservice的url后點擊移至
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
選擇同步
在这里插入图片描述
如圖表示調用webservice成功
在这里插入图片描述
二、調用webservice中的方法

(1)在Startup.cs中ConfigureServices註冊webservice服務

    1

services.AddSingleton<ServiceReference1.CommServiceSoap>(new ServiceReference1.CommServiceSoapClient(ServiceReference1.CommServiceSoapClient.EndpointConfiguration.CommServiceSoap));

    1

在这里插入图片描述

(2)在controller中引用

 public class LoginController : ControllerBase
    {

        private CommServiceSoap _webService;

        /// <summary>
        /// 在构造函数注入实例
        /// </summary>
        /// <param name="serivce"></param>
        public LoginController(CommServiceSoap serivce)
        {
            _webService = serivce;
        }

        [HttpPost("Login")]
        public ActionResult<bool> Login(UserModel user)
        {
            string empno = user.Empno;
            string empPwd = user.EmpPwd;
            bool x = _webService.LoginByAD(empno, empPwd);       //引用webservice中的方法   
            return x;

        }
    }
————————————————
版权声明:本文为CSDN博主「辣辣lalala」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43671185/article/details/103157774

 

终于找到的了,会英语编程和不会英语编程果然是两个世界的

https://blog.csdn.net/u010067685/article/details/78915747   感谢这位兄弟


 

  • using System;
  • using System.Web;
  • using System.Xml;
  • using System.Collections;
  • using System.Net;
  • using System.Text;
  • using System.IO;
  • using System.Xml.Serialization;
  •  
  •  
  • /// <summary>
  • /// 利用WebRequest/WebResponse进行WebService调用的类
  • /// </summary>
  • public class WebServiceHelper
  • {
  • //<webServices>
  • // <protocols>
  • // <add name="HttpGet"/>
  • // <add name="HttpPost"/>
  • // </protocols>
  • //</webServices>
  • private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
  •  
  • /// <summary>
  • /// 需要WebService支持Post调用
  • /// </summary>
  • public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
  • {
  • HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
  • request.Method = "POST";
  • request.ContentType = "application/x-www-form-urlencoded";
  • SetWebRequest(request);
  • byte[] data = EncodePars(Pars);
  • WriteRequestData(request, data);
  • return ReadXmlResponse(request.GetResponse());
  • }
  •  
  • /// <summary>
  • /// 需要WebService支持Get调用
  • /// </summary>
  • public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
  • {
  • HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
  • request.Method = "GET";
  • request.ContentType = "application/x-www-form-urlencoded";
  • SetWebRequest(request);
  • return ReadXmlResponse(request.GetResponse());
  • }
  •  
  •  
  • /// <summary>
  • /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
  • /// </summary>
  • public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
  • {
  • if (_xmlNamespaces.ContainsKey(URL))
  • {
  • return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
  • }
  • else
  • {
  • return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
  • }
  • }
  •  
  • /// <summary>
  • /// 通用WebService调用(Soap)
  • /// </summary>
  • /// <param name="URL"></param>
  • /// <param name="MethodName"></param>
  • /// <param name="Pars"></param>
  • /// <param name="XmlNs"></param>
  • /// <returns></returns>
  • private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
  • {
  • _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
  • HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
  • request.Method = "POST";
  • request.ContentType = "text/xml; charset=utf-8";
  • request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
  • SetWebRequest(request);
  • byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
  • WriteRequestData(request, data);
  • XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
  • doc = ReadXmlResponse(request.GetResponse());
  • XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
  • mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
  • String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
  • doc2.LoadXml("<root>" + RetXml + "</root>");
  • AddDelaration(doc2);
  • return doc2;
  • }
  •  
  • /// <summary>
  • /// 通过WebService的WSDL获取XML名称空间
  • /// </summary>
  • /// <param name="URL"></param>
  • /// <returns></returns>
  • private static string GetNamespace(String URL)
  • {
  • HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
  • SetWebRequest(request);
  • WebResponse response = request.GetResponse();
  • StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  • XmlDocument doc = new XmlDocument();
  • doc.LoadXml(sr.ReadToEnd());
  • sr.Close();
  • return doc.SelectSingleNode("//@targetNamespace").Value;
  • }
  •  
  • /// <summary>
  • /// 动态生成SOP请求报文内容
  • /// </summary>
  • /// <param name="Pars"></param>
  • /// <param name="XmlNs"></param>
  • /// <param name="MethodName"></param>
  • /// <returns></returns>
  • private static byte[] EncodeParsToSoap(Hashtable Pars, 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>");
  • AddDelaration(doc);
  • 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 Pars.Keys)
  • {
  • XmlElement soapPar = doc.CreateElement(k);
  • soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
  • soapMethod.AppendChild(soapPar);
  • }
  • soapBody.AppendChild(soapMethod);
  • doc.DocumentElement.AppendChild(soapBody);
  • return Encoding.UTF8.GetBytes(doc.OuterXml);
  • }
  •  
  • /// <summary>
  • /// 将对象转换成XML节点格式
  • /// </summary>
  • /// <param name="o"></param>
  • /// <returns></returns>
  • private static string ObjectToSoapXml(object o)
  • {
  • XmlSerializer mySerializer = new XmlSerializer(o.GetType());
  • MemoryStream ms = new MemoryStream();
  • mySerializer.Serialize(ms, o);
  • XmlDocument doc = new XmlDocument();
  • doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
  • if (doc.DocumentElement != null)
  • {
  • return doc.DocumentElement.InnerXml;
  • }
  • else
  • {
  • return o.ToString();
  • }
  • }
  •  
  • /// <summary>
  • /// 设置WEB请求
  • /// </summary>
  • /// <param name="request"></param>
  • private static void SetWebRequest(HttpWebRequest request)
  • {
  • request.Credentials = CredentialCache.DefaultCredentials;
  • request.Timeout = 10000;
  • }
  •  
  • /// <summary>
  • /// 设置请求数据
  • /// </summary>
  • /// <param name="request"></param>
  • /// <param name="data"></param>
  • private static void WriteRequestData(HttpWebRequest request, byte[] data)
  • {
  • request.ContentLength = data.Length;
  • Stream writer = request.GetRequestStream();
  • writer.Write(data, 0, data.Length);
  • writer.Close();
  • }
  •  
  • /// <summary>
  • /// 获取字符串的UTF8码字符串
  • /// </summary>
  • /// <param name="Pars"></param>
  • /// <returns></returns>
  • private static byte[] EncodePars(Hashtable Pars)
  • {
  • return Encoding.UTF8.GetBytes(ParsToString(Pars));
  • }
  •  
  • /// <summary>
  • /// 将Hashtable转换成WEB请求键值对字符串
  • /// </summary>
  • /// <param name="Pars"></param>
  • /// <returns></returns>
  • private static String ParsToString(Hashtable Pars)
  • {
  • StringBuilder sb = new StringBuilder();
  • foreach (string k in Pars.Keys)
  • {
  • if (sb.Length > 0)
  • {
  • sb.Append("&");
  • }
  • sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
  • }
  • return sb.ToString();
  • }
  •  
  • /// <summary>
  • /// 获取Webservice响应报文XML
  • /// </summary>
  • /// <param name="response"></param>
  • /// <returns></returns>
  • private static XmlDocument ReadXmlResponse(WebResponse response)
  • {
  • StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  • String retXml = sr.ReadToEnd();
  • sr.Close();
  • XmlDocument doc = new XmlDocument();
  • doc.LoadXml(retXml);
  • return doc;
  • }
  •  
  • /// <summary>
  • /// 设置XML文档版本声明
  • /// </summary>
  • /// <param name="doc"></param>
  • private static void AddDelaration(XmlDocument doc)
  • {
  • XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
  • doc.InsertBefore(decl, doc.DocumentElement);
  • }
  • }
     
    最后整理一个自己用的请求WebService 请求方法,免得以后又要满世界找
    https://blog.csdn.net/sun_zeliang/article/details/81587835 参考请求帮助
     public static string RequestWebService(string url, string methodname, Hashtable Pars)
            {


                HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromSeconds(10000);
                HttpResponseMessage requestSOA = client.GetAsync(url + "?WSDL").Result;
                requestSOA.EnsureSuccessStatusCode();
                string strSOAPAction = string.Empty;
                XmlDocument docSOA = new XmlDocument();
                docSOA.LoadXml(requestSOA.Content.ReadAsStringAsync().Result);
                strSOAPAction = docSOA.SelectSingleNode("//@targetNamespace").Value;


                #region 动态生成SOP请求报文内容
                XmlDocument docReqContex = new XmlDocument();
                XmlDeclaration decl = docReqContex.CreateXmlDeclaration("1.0", "utf-8", null);
                docReqContex.InsertBefore(decl, docReqContex.DocumentElement);

                docReqContex.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>");
                XmlElement soapBody = docReqContex.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
                XmlElement soapMethod = docReqContex.CreateElement(methodname);
                soapMethod.SetAttribute("xmlns", strSOAPAction);

                foreach (string k in Pars.Keys)
                {
                    XmlElement soapPar = docReqContex.CreateElement(k);

                    object objParsKey = Pars[k];
                    #region 将对象转换成XML节点格式
                    XmlSerializer mySerializer = new XmlSerializer(objParsKey.GetType());
                    using (MemoryStream ms = new MemoryStream())
                    {
                        mySerializer.Serialize(ms, objParsKey);
                        XmlDocument docObjXML = new XmlDocument();
                        docObjXML.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
                        if (docObjXML.DocumentElement != null)
                        {
                            soapPar.InnerXml = docObjXML.DocumentElement.InnerXml;
                        }
                        else
                        {
                            soapPar.InnerXml = objParsKey.ToString();
                        }
                    }
                    #endregion
                    soapMethod.AppendChild(soapPar);

                }
                soapBody.AppendChild(soapMethod);
                docReqContex.DocumentElement.AppendChild(soapBody);
                byte[] data = Encoding.UTF8.GetBytes(docReqContex.OuterXml);
                #endregion


                HttpClient requestClient = new HttpClient();
                requestClient.Timeout = TimeSpan.FromSeconds(10000);

                HttpContent requestcontent = new StringContent(docReqContex.OuterXml);

                //设置Http的内容标头
                requestcontent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");
                //设置Http的内容标头的字符
                requestcontent.Headers.ContentType.CharSet = "utf-8";

                requestcontent.Headers.Add("SOAPAction", "\"" + strSOAPAction + (strSOAPAction.EndsWith("/") ? "" : "/") + methodname + "\"");
                //由HttpClient发出异步Post请求
               
                HttpResponseMessage requestMessage = requestClient.PostAsync(url, requestcontent).Result;
                requestMessage.EnsureSuccessStatusCode();
                XmlDocument docReq = new XmlDocument();
                string xmlRes=  requestMessage.Content.ReadAsStringAsync().Result;
                docReq.LoadXml(xmlRes);


               
                XmlNamespaceManager mgr = new XmlNamespaceManager(docReq.NameTable);
                mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
                String RetXml = docReq.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;

                return RetXml;
            }

 关于在.Net Framework 4.6 以下使用 该方法

public static string WebRequestWebService(string url, string methodname, Hashtable Pars)
        {
       
           WebRequest client =HttpWebRequest.CreateHttp(url + "?WSDL"); 
            client.Timeout =1000*10;
            client.Method = "GET";
            string strSOAPAction = String.Empty;
            using (WebResponse requestSOA = client.GetResponse()) 
            {
           
                StreamReader reader = new StreamReader(requestSOA.GetResponseStream(), Encoding.UTF8);
                strSOAPAction = reader.ReadToEnd().Trim();
                XmlDocument docSOA = new XmlDocument();
                docSOA.LoadXml(strSOAPAction);
                strSOAPAction = docSOA.SelectSingleNode("//@targetNamespace").Value;
            }
            if (string.IsNullOrWhiteSpace(strSOAPAction)) 
            {
                return "无法获取请求报文内容!";
            }
            #region 动态生成SOP请求报文内容
            XmlDocument docReqContex = new XmlDocument();
            XmlDeclaration decl = docReqContex.CreateXmlDeclaration("1.0", "utf-8", null);
            docReqContex.InsertBefore(decl, docReqContex.DocumentElement);

            docReqContex.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>");
            XmlElement soapBody = docReqContex.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
            XmlElement soapMethod = docReqContex.CreateElement(methodname);
            soapMethod.SetAttribute("xmlns", strSOAPAction);

            foreach (string k in Pars.Keys)
            {
                XmlElement soapPar = docReqContex.CreateElement(k);

                object objParsKey = Pars[k];
                #region 将对象转换成XML节点格式
                XmlSerializer mySerializer = new XmlSerializer(objParsKey.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    mySerializer.Serialize(ms, objParsKey);
                    XmlDocument docObjXML = new XmlDocument();
                    docObjXML.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
                    if (docObjXML.DocumentElement != null)
                    {
                        soapPar.InnerXml = docObjXML.DocumentElement.InnerXml;
                    }
                    else
                    {
                        soapPar.InnerXml = objParsKey.ToString();
                    }
                }
                #endregion
                soapMethod.AppendChild(soapPar);
            }
            soapBody.AppendChild(soapMethod);
            docReqContex.DocumentElement.AppendChild(soapBody);
           
            #endregion 动态生成SOP请求报文内容


            WebRequest requestClient = HttpWebRequest.CreateHttp(url);
            requestClient.Timeout = 1000 * 10;
            requestClient.Method = "POST";
            requestClient.ContentType = "text/xml";
            requestClient.Headers["Accept-Charset"] = "utf-8";
            requestClient.Headers.Add("SOAPAction", "\"" + strSOAPAction + (strSOAPAction.EndsWith("/") ? "" : "/") + methodname + "\"");
            //发送数据
            using (System.IO.Stream newStream = requestClient.GetRequestStream()) 
            {
                byte[] data = Encoding.UTF8.GetBytes(docReqContex.OuterXml);
                newStream.Write(data, 0, data.Length);
                WebResponse sentReqData = requestClient.GetResponse();
                newStream.Close();
            }
            String RetXml = String.Empty;
            //获取响应
            WebResponse myResponse = requestClient.GetResponse();
            using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) 
            {
                string content = reader.ReadToEnd().Trim();
                XmlDocument docReq = new XmlDocument();
                string xmlRes = content;
                docReq.LoadXml(xmlRes);
                XmlNamespaceManager mgr = new XmlNamespaceManager(docReq.NameTable);
                mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
                 RetXml = docReq.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
            }

            return RetXml;
        }

 

调用

 Hashtable reqData = new Hashtable();//请求参数
            reqData.Add("USER", "TEST");
          
            WebRequestWebService("http://is1fax.hct.com.tw/Webedi_Erstno_NEW/WS_addrCompare1.asmx", "addrCompare_string", reqData);

 

https://blog.csdn.net/hatchgavin/article/details/52172927

 

 HttpWebRequest第一次请求很慢超时的原因

 

在使用HttpWebRequest建立http请求时,第一次连接的响应速度会很慢,而且还会出现请求超时的错误,这里大概有十几秒钟的等待时间,但是一旦第一次运行成功后,下面的请求页面速度就会很快了。

我发现的两种解决方法:

1.IE浏览器设置

 打开IE浏览器---》工具---》Internet选项---》连接--》局域网设置---》自动检测设置的勾去掉。

2. 这是重点

WebClient.Proxy = null; 或 HttpWebRequest.Proxy = null;

 

 

posted @ 2021-05-04 11:30  LuoCore  阅读(3402)  评论(0编辑  收藏  举报