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;

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM