C# 动态调用http及 webservice服务
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace Test { public class RestfullRequest { public static string Request(string url, string method, string contentType, string data, NameValueCollection header=null,NetworkCredential credential=null, string proxyAddress = null, Encoding responseEncoding= null) { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType; if (header != null) request.Headers.Add(header); if (credential != null) request.Credentials = credential; if (!string.IsNullOrEmpty(proxyAddress)) { IWebProxy proxy = new WebProxy(proxyAddress); proxy.Credentials = new NetworkCredential(); request.Proxy = proxy; } if (!string.IsNullOrEmpty(data)) { using (var swt = new StreamWriter(request.GetRequestStream())) { swt.Write(data); } } string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response.ContentType.IndexOf("octet-stream") > -1) { string dispositionStr = response.Headers["Content-Disposition"]; int fileNameI = dispositionStr.IndexOf("filename="); string fileName = dispositionStr.Substring(fileNameI + 9, dispositionStr.Length - (fileNameI + 9)); fileName = HttpUtility.UrlDecode(fileName, Encoding.UTF8); string downpath = AppDomain.CurrentDomain.BaseDirectory + "Download"; if (!Directory.Exists(downpath)) { Directory.CreateDirectory(downpath); } string downFile= downpath + "\\" + fileName; if (File.Exists(downFile)) { File.Delete(downFile); } Stream inStream = response.GetResponseStream(); using (Stream outStream = File.OpenWrite(downFile)) { byte[] buffer = new byte[8192]; int size = 0; while ((size = inStream.Read(buffer, 0, 8192)) > 0) { outStream.Write(buffer, 0, size); } } result = downFile; } else {
Stream stream = response.GetResponseStream();
if (responseEncoding == null) responseEncoding = Encoding.UTF8;
StreamReader myStreamReader = new StreamReader(stream, responseEncoding);
result = myStreamReader.ReadToEnd();
myStreamReader.Close();
stream.Close();
//byte[] buf = new byte[1024];
//while (true)
//{
// int len = stream.Read(buf, 0, buf.Length);
// if (len <= 0)//len <= 0 跳出循环
// break;
// if (responseEncoding == null) responseEncoding = Encoding.UTF8;
// result += responseEncoding.GetString(buf, 0, len);//指定编码格式
//}
} //using (var sr = new StreamReader(response.GetResponseStream())) //{ // result = sr.ReadToEnd(); //} } return result; } public static bool IsFileInUse(string fileName) { bool inUse = true; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { } finally { if (fs != null) fs.Close(); } return inUse;//true表示正在使用,false没有使用 } } }
下面是调用:asmx(webservice)
using Microsoft.CSharp; using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Services.Description; namespace Test { /// <summary> /// 动态调用WebService的帮助类 /// </summary> public class WebServiceHelper { #region InvokeWebService /// < summary> /// 动态调用web服务 ///< /summary> /// < param name="url">WSDL服务地址< /param> /// < param name="methodname">方法名< /param> /// < param name="args">参数< /param> /// < returns>< /returns> public object InvokeWebService(string url, string methodname, object[] args) { return this.InvokeWebService(url, null, methodname, args); } /// < summary> /// 动态调用web服务 /// < /summary> /// < param name="url">WSDL服务地址< /param> /// < param name="classname">类名< /param> /// < param name="methodname">方法名< /param> /// < param name="args">参数< /param> /// < returns>< /returns> public object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); if (!url.ToUpper().Contains("WSDL")) { url = string.Format("{0}?{1}", url, "WSDL"); } Stream stream = wc.OpenRead(url); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider icc = new CSharpCodeProvider(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } } private static string GetWsClassName(string wsUrl) { string[] parts = wsUrl.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); if (pps[0].Contains("?")) { return pps[0].Split('?')[0]; } return pps[0]; } #endregion } }
调用:
WebServiceHelper webService = new WebServiceHelper(); object obj= webService.InvokeWebService("http://127.0.0.1:8001/WebService1.asmx", "Add", new object[] {22,33 }); DataTable dt = obj as DataTable;
https://www.jb51.net/article/190211.htm