在.net中调用别人写的接口获得数据

在项目开发中遇到了两个团队进行开发,在开发中后台需要调用到另外一个团队写的接口再进行逻辑处理。

当然这些调用POST、GET跟调用微信和支付宝的接口都是一致的大笑。下面是我整理的调用方法。

话不多说,直接放代码:

 

[csharp] view plain copy
  1. SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();  
  2. sParaTemp.Add("1",参数变量);  
  3. sParaTemp.Add("4", 参数变量);  
  4. sParaTemp.Add("2", 参数变量);  
  5. sParaTemp.Add("3", 参数变量);  
  6. //得到序列化的参数值  
  7. string data = NetFramework.Helper.wphttppost.datapost(sParaTemp);  
  8. //进行post提交  
  9. string result = NetFramework.Helper.wphttppost.Post(data, "http://121.22.22.22/接口地址", 6);  



 

-------------------------------------------------------------------------------------------------------

[csharp] view plain copy
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Web;  
    4. using System.Net;  
    5. using System.IO;  
    6. using System.Text;  
    7. using System.Net.Security;  
    8. using System.Security.Authentication;  
    9. using System.Security.Cryptography.X509Certificates;  
    10.   
    11.   
    12. namespace NetFramework.Helper  
    13. {  
    14.     public class wphttppost  
    15.     {  
    16.   
    17.   
    18.         public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)  
    19.         {  
    20.             //直接确认,否则打不开      
    21.             return true;  
    22.         }  
    23.   
    24.   
    25.         /// <summary>  
    26.         /// 得到需要传递的参数格式  
    27.         /// </summary>  
    28.         /// <param name="sParaTemp">参数键值</param>  
    29.         /// <returns></returns>  
    30.         public static string datapost(SortedDictionary<string, string> sParaTemp)  
    31.         {  
    32.             Encoding myEncoding = Encoding.GetEncoding("gb2312");    
    33.             StringBuilder prestr = new StringBuilder();  
    34.             foreach (KeyValuePair<string, string> temp in sParaTemp)  
    35.             {  
    36.                 prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value, myEncoding) + "&");  
    37.             }  
    38.   
    39.   
    40.             //去掉最後一個&字符  
    41.             int nLen = prestr.Length;  
    42.             prestr.Remove(nLen - 1, 1);  
    43.   
    44.   
    45.             return prestr.ToString();  
    46.         }  
    47.   
    48.   
    49.         /// <summary>  
    50.         /// post方式提交  
    51.         /// </summary>  
    52.         /// <param name="postdata">传递的参数先调用datapost()方法</param>  
    53.         /// <param name="url">访问的地址</param>  
    54.         /// <param name="timeout">超时时间 6</param>  
    55.         /// <returns></returns>  
    56.         public static string Post(string postdata, string url, int timeout)  
    57.         {  
    58.             Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("postdata: {0} url: {1} timeout:{2}", postdata, url, timeout));  
    59.             System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接  
    60.   
    61.   
    62.             string result = "";//返回结果  
    63.   
    64.   
    65.             HttpWebRequest request = null;  
    66.             HttpWebResponse response = null;  
    67.             Stream reqStream = null;  
    68.   
    69.   
    70.             try  
    71.             {  
    72.                 //设置最大连接数  
    73.                 ServicePointManager.DefaultConnectionLimit = 200;  
    74.                 //设置https验证方式  
    75.                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))  
    76.                 {  
    77.                     ServicePointManager.ServerCertificateValidationCallback =  
    78.                             new RemoteCertificateValidationCallback(CheckValidationResult);  
    79.                 }  
    80.   
    81.   
    82.                 /*************************************************************** 
    83.                 * 下面设置HttpWebRequest的相关属性 
    84.                 * ************************************************************/  
    85.                 request = (HttpWebRequest)WebRequest.Create(url);  
    86.   
    87.   
    88.                 request.Method = "POST";  
    89.                 request.Timeout = timeout * 1000;  
    90.   
    91.   
    92.                 //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据  
    93.                 request.ServicePoint.Expect100Continue = false;  
    94.   
    95.   
    96.                 //设置代理服务器  
    97.                 //WebProxy proxy = new WebProxy();                          //定义一个网关对象  
    98.                 //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //网关服务器端口:端口  
    99.                 //request.Proxy = proxy;  
    100.   
    101.   
    102.                 //设置POST的数据类型和长度  
    103.                 request.ContentType = "application/x-www-form-urlencoded;charset=gb2312";  
    104.                 byte[] data = System.Text.Encoding.UTF8.GetBytes(postdata);  
    105.                 request.ContentLength = data.Length;  
    106.   
    107.   
    108.                 ////是否使用证书  
    109.                 //if (isUseCert)  
    110.                 //{  
    111.                 //    string path = HttpContext.Current.Request.PhysicalApplicationPath;  
    112.                 //    X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);  
    113.                 //    request.ClientCertificates.Add(cert);  
    114.                 //    //Log.Debug("WxPayApi", "PostXml used cert");  
    115.                 //}  
    116.   
    117.   
    118.                 //往服务器写入数据  
    119.                 reqStream = request.GetRequestStream();  
    120.                 reqStream.Write(data, 0, data.Length);  
    121.                 reqStream.Close();  
    122.   
    123.   
    124.                 //获取服务端返回  
    125.                 response = (HttpWebResponse)request.GetResponse();  
    126.   
    127.   
    128.                 //获取服务端返回数据  
    129.                 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
    130.                 result = sr.ReadToEnd().Trim();  
    131.                 sr.Close();  
    132.             }  
    133.             catch (System.Threading.ThreadAbortException e)  
    134.             {  
    135.                 //Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");  
    136.                 Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("Exception message: {0}", e.Message));  
    137.                 System.Threading.Thread.ResetAbort();  
    138.             }  
    139.             catch (WebException e)  
    140.             {  
    141.                 //Log.Error("HttpService", e.ToString());  
    142.                 //if (e.Status == WebExceptionStatus.ProtocolError)  
    143.                 //{  
    144.                     //Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);  
    145.                     //Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);  
    146.                 //}  
    147.                 //throw new WxPayException(e.ToString());  
    148.                 Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("WebException message: {0}", e.Message));  
    149.             }  
    150.             catch (Exception e)  
    151.             {  
    152.                 Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("Exception message: {0}", e.Message));  
    153.                 //Log.Error("HttpService", e.ToString());  
    154.                 //throw new WxPayException(e.ToString());  
    155.             }  
    156.             finally  
    157.             {  
    158.                 //关闭连接和流  
    159.                 if (response != null)  
    160.                 {  
    161.                     response.Close();  
    162.                 }  
    163.                 if (request != null)  
    164.                 {  
    165.                     request.Abort();  
    166.                 }  
    167.             }  
    168.             return result;  
    169.         }  
    170.   
    171.   
    172.         /// <summary>  
    173.         /// 处理http GET请求,返回数据  
    174.         /// </summary>  
    175.         /// <param name="url">请求的url地址</param>  
    176.         /// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>  
    177.         public static string Get(string url)  
    178.         {  
    179.             System.GC.Collect();  
    180.             string result = "";  
    181.   
    182.   
    183.             HttpWebRequest request = null;  
    184.             HttpWebResponse response = null;  
    185.   
    186.   
    187.             //请求url以获取数据  
    188.             try  
    189.             {  
    190.                 //设置最大连接数  
    191.                 ServicePointManager.DefaultConnectionLimit = 200;  
    192.                 //设置https验证方式  
    193.                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))  
    194.                 {  
    195.                     ServicePointManager.ServerCertificateValidationCallback =  
    196.                             new RemoteCertificateValidationCallback(CheckValidationResult);  
    197.                 }  
    198.   
    199.   
    200.                 /*************************************************************** 
    201.                 * 下面设置HttpWebRequest的相关属性 
    202.                 * ************************************************************/  
    203.                 request = (HttpWebRequest)WebRequest.Create(url);  
    204.   
    205.   
    206.                 request.Method = "GET";  
    207.   
    208.   
    209.                 //设置代理  
    210.                 //WebProxy proxy = new WebProxy();  
    211.                 //proxy.Address = new Uri(WxPayConfig.PROXY_URL);  
    212.                 //request.Proxy = proxy;  
    213.   
    214.   
    215.                 //获取服务器返回  
    216.                 response = (HttpWebResponse)request.GetResponse();  
    217.   
    218.   
    219.                 //获取HTTP返回数据  
    220.                 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
    221.                 result = sr.ReadToEnd().Trim();  
    222.                 sr.Close();  
    223.             }  
    224.             catch (System.Threading.ThreadAbortException e)  
    225.             {  
    226.                 //Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");  
    227.                 //Log.Error("Exception message: {0}", e.Message);  
    228.                 System.Threading.Thread.ResetAbort();  
    229.             }  
    230.             catch (WebException e)  
    231.             {  
    232.                 //Log.Error("HttpService", e.ToString());  
    233.                 //if (e.Status == WebExceptionStatus.ProtocolError)  
    234.                 //{  
    235.                 //    Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);  
    236.                 //    Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);  
    237.                 //}  
    238.                 //throw new WxPayException(e.ToString());  
    239.             }  
    240.             catch (Exception e)  
    241.             {  
    242.                 //Log.Error("HttpService", e.ToString());  
    243.                 //throw new WxPayException(e.ToString());  
    244.             }  
    245.             finally  
    246.             {  
    247.                 //关闭连接和流  
    248.                 if (response != null)  
    249.                 {  
    250.                     response.Close();  
    251.                 }  
    252.                 if (request != null)  
    253.                 {  
    254.                     request.Abort();  
    255.                 }  
    256.             }  
    257.             return result;  
    258.         }  
    259.     }  
posted @ 2018-04-10 13:39  KJXY  阅读(133)  评论(0)    收藏  举报