接口调用帮助类(http调接口、WebService动态调接口)

1.HttpGetPost调用接口实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Net;
 6 using System.IO;
 7 
 8 namespace Helper
 9 {
10    public class HttpGetPostHelper
11     {
12        /// <summary>
13        /// HttpGet
14        /// </summary>
15        /// <param name="url"></param>
16        /// <returns></returns>
17        public static string HttpGet(string url)
18        {
19            string result = string.Empty;
20            HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
21            wbRequest.Method = "GET";
22            HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
23            using (Stream responseStream = wbResponse.GetResponseStream())
24            {
25                using (StreamReader sReader = new StreamReader(responseStream))
26                {
27                    result = sReader.ReadToEnd();
28                }
29            }
30            return result;
31        }
32        /// <summary>
33        /// HttpPost
34        /// </summary>
35        /// <param name="url"></param>
36        /// <param name="paramData">参数(若是对象可使用Json格式)</param>
37        /// <param name="headerDic">请求头</param>
38        /// <returns></returns>
39        public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic)
40        {
41            string result = string.Empty;
42            HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
43            wbRequest.Method = "POST";
44            wbRequest.ContentType = "application/json";// "application/x-www-form-urlencoded";
45            wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
46            
47            if (headerDic != null && headerDic.Count > 0)
48            {
49                foreach (var item in headerDic)
50                {
51                    wbRequest.Headers.Add(item.Key, item.Value);
52                }
53            }
54            using (Stream requestStream = wbRequest.GetRequestStream())
55            {
56                using (StreamWriter swrite = new StreamWriter(requestStream))
57                {
58                    swrite.Write(paramData);
59                }
60            }
61            HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
62            using (Stream responseStream = wbResponse.GetResponseStream())
63            {
64                using (StreamReader sread = new StreamReader(responseStream))
65                {
66                    result = sread.ReadToEnd();
67                }
68            }
69            return result;
70        }
71     }
72 }
View Code

2.WebService动态调接口

  1 using System.Collections.Generic;
  2 using System.Linq;
  3 using System.Text;
  4 using System.Net;
  5 using System.IO;
  6 using System;
  7 using System.Web.Services.Description; //WS的描述 
  8 using System.CodeDom;
  9 using System.CodeDom.Compiler;
 10 using System.Reflection;
 11 using Microsoft.CSharp;
 12 
 13 
 14 namespace MYToOtherInterface.Domain
 15 {
 16     /// <summary>
 17     /// Webservices测试
 18     /// </summary>
 19     public static class WebServiceHelper
 20     {
 21  /// <summary>
 22         /// 调用Webservice
 23         /// </summary>
 24         /// <param name="methodName">方法名</param>
 25         /// <param name="addParams">参数数组</param>
 26        /// <param name="headerDic">请求头</param>
 27         /// <returns></returns>
 28         public static string InvokeWebservice(string WebserviceUrl, string methodName, object[] addParams, Dictionary<string, string> headerDic)
 29         {
 30 
 31             //服务地址,该地址可以放到程序的配置文件中,这样即使服务地址改变了,也无须重新编译程序。
 32           
 33             //< add key = "WebService252" value = "http ://10.5.107.16:9002/OpenApi/SlxtService.asmx" />
 34             string url = WebserviceUrl;
 35             if (string.IsNullOrEmpty(url))
 36             {
 37                 throw new Exception("接口地址未配置!");
 38             }
 39             //客户端代理服务命名空间,可以设置成需要的值。  
 40             string ns = string.Format("ProxyServiceReference");
 41 
 42             if (!url.ToUpper().Contains("?WSDL"))
 43             {
 44                 url = url + "?wsdl";
 45             }
 46             //获取WSDL  
 47             WebClient wc = new WebClient();
 48             
 49             Stream stream = wc.OpenRead(url);
 50             if (headerDic != null && headerDic.Count > 0)
 51             {
 52                 foreach (var item in headerDic)
 53                 {
 54                     wc.Headers.Add(item.Key, item.Value);
 55                 }
 56             }
 57             ServiceDescription sd = ServiceDescription.Read(stream);//服务的描述信息都可以通过ServiceDescription获取  
 58             string classname = sd.Services[0].Name;
 59 
 60             ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
 61             sdi.AddServiceDescription(sd, "", "");
 62             CodeNamespace cn = new CodeNamespace(ns);
 63             
 64             //生成客户端代理类代码  
 65             CodeCompileUnit ccu = new CodeCompileUnit();
 66             ccu.Namespaces.Add(cn);
 67             sdi.Import(cn, ccu);
 68             CSharpCodeProvider csc = new CSharpCodeProvider();
 69 
 70             //设定编译参数  
 71             CompilerParameters cplist = new CompilerParameters();
 72             cplist.GenerateExecutable = false;
 73             cplist.GenerateInMemory = true;
 74             cplist.ReferencedAssemblies.Add("System.dll");
 75             cplist.ReferencedAssemblies.Add("System.XML.dll");
 76             cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
 77             cplist.ReferencedAssemblies.Add("System.Data.dll");
 78 
 79             //编译代理类  
 80             CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
 81             if (cr.Errors.HasErrors == true)
 82             {
 83                 System.Text.StringBuilder sb = new System.Text.StringBuilder();
 84                 foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
 85                 {
 86                     sb.Append(ce.ToString());
 87                     sb.Append(System.Environment.NewLine);
 88                 }
 89                 throw new ArgumentException(sb.ToString());
 90             }
 91             //生成代理实例,并调用方法  
 92             Assembly assembly = cr.CompiledAssembly;
 93             Type t = assembly.GetType(ns + "." + classname, true, true);
 94             object obj = Activator.CreateInstance(t);
 95 
 96             //调用方法  
 97             MethodInfo add = t.GetMethod(methodName);
 98             object addReturn = add.Invoke(obj, addParams);
 99             var s = addReturn.ToString();
100             return s;
101         }
102 
103     }
104 }
View Code

 

posted @ 2019-11-20 17:40  慕夜h  阅读(433)  评论(0编辑  收藏  举报