WebApiTools.cs - WebApi客户端调用Web Api接口工具类


WebApiTools.cs - WebApi客户端调用Web Api接口工具类

WebApiTools类接口方法

WebApiTools

WebApiTools类完整代码

C# 全选
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;

namespace CSFramework.WebApi.Core
{
    /// <summary>
    /// WebApi客户端调用工具类
    /// </summary>
    public static class WebApiTools
    {
        static WebApiTools()
        {
            WebApiTools.TimeOut = 5 * 60 * 1000;//3分钟超时
        }

        /// <summary>
        /// Http请求超时时间
        /// </summary>
        public static int TimeOut { get; set; }

        /// <summary>
        /// 预设的POST方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Post(string url, string data)
        {
            return Post(url, data, "application/json;charset=UTF-8");
        }

        /// <summary>
        /// 预设的GET方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Get(string url, string param)
        {
            return Get(url, param, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 客户端统一提交数据
        /// </summary>
        /// <param name="url">WebAPI核心URL地址</param>
        /// <param name="data">提交的数据</param>
        /// <param name="contentType">指定request.ContentType</param>
        /// <returns>返回数据</returns>
        public static string Post(string url, string data, string contentType)
        {
            string returnData = null;
            try
            {
                string strURL = url;
                System.Net.HttpWebRequest request;

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    ServicePointManager.CheckCertificateRevocationList = false;
                    ServicePointManager.DefaultConnectionLimit = 512;
                    ServicePointManager.Expect100Continue = false;

                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                    request.KeepAlive = false;
                }
                else
                {
                    request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                }
                
                request.Method = "POST";
                request.ContentType = contentType;// "application/json;charset=UTF-8";//POST必须使用JSON格式
                string paraUrlCoded = data;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                request.Timeout = WebApiTools.TimeOut;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                string StrDate = "";
                string strValue = "";
                StreamReader Reader = new StreamReader(s, Encoding.GetEncoding("utf-8"));
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate + "\r\n";
                }
                returnData = strValue;
                return returnData.Trim() + "\n";
            }
            catch (WebException ex)
            {
                string result = "POST:操作失败!\r\n" + ex.Message;
                if (ex.Response != null)
                    result = result + "\r\n" + GetResponseText(ex.Response);
                throw new Exception(result);
            }
            catch (Exception ex)
            {
                throw new Exception("POST:操作失败!\r\n" + ex.Message);
            }
        }

        private static string GetResponseText(WebResponse response)
        {
            string text;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                text = sr.ReadToEnd();
            }

            if ((response is HttpWebResponse))
            {
                int status = (int)(response as HttpWebResponse).StatusCode;
                if (status == 429) text = "流量访问限制!" + text;
            }

            return text;
        }


        /// <summary>
        /// 客户端统一提交数据
        /// </summary>
        /// <param name="url">WebAPI核心URL地址</param>
        /// <param name="param">URL参数</param>
        /// <returns>返回数据</returns>
        public static string Get(string url, string param, string contentType)
        {
            try
            {

                System.Net.HttpWebRequest request;

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    ServicePointManager.CheckCertificateRevocationList = false;
                    ServicePointManager.DefaultConnectionLimit = 512;
                    ServicePointManager.Expect100Continue = false;

                    request = WebRequest.Create(url + (param == "" ? "" : "?") + param) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                    request.KeepAlive = false;
                }
                else
                {
                    request = (System.Net.HttpWebRequest)WebRequest.Create(url + (param == "" ? "" : "?") + param);
                }


                //request = (HttpWebRequest)WebRequest.Create(url + (param == "" ? "" : "?") + param);
                request.Method = "GET";
                request.ContentType = contentType;//text/html;charset=UTF-8;

                #region 获取网页内容太大的话,就加下面这两句代码
                request.Headers["Accept-Encoding"] = "gzip,deflate";
                request.AutomaticDecompression = DecompressionMethods.GZip;
                #endregion

                request.Timeout = WebApiTools.TimeOut;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch (WebException ex)
            {
                string result = "GET:操作失败!\r\n" + ex.Message;
                if (ex.Response != null)
                    result = result + "\r\n" + GetResponseText(ex.Response);
                throw new Exception(result);
            }
            catch (Exception ex)
            {
                throw new Exception("GET:操作失败!\r\n" + ex.Message);
            }
        }

        /// <summary>
        /// 获取图片资源
        /// </summary>
        /// <param name="url">图片网址</param>
        /// <returns></returns>
        public static Image GetImage(string url)
        {
            try
            {
                var request = WebRequest.Create(url);
                request.Timeout = WebApiTools.TimeOut;
                using (var response = request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        return Bitmap.FromStream(stream);
                    }
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取服务器请求,返回Stream对象。
        /// </summary>
        /// <param name="url">服务器地址</param>
        /// <param name="param">URL参数</param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static Stream GetResponse(string url, string param, string contentType)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (param == "" ? "" : "?") + param);
                request.Method = "GET";
                request.ContentType = contentType;//text/html;charset=UTF-8;

                #region 获取网页内容太大的话,就加下面这两句代码
                request.Headers["Accept-Encoding"] = "gzip,deflate";
                request.AutomaticDecompression = DecompressionMethods.GZip;
                #endregion

                request.Timeout = WebApiTools.TimeOut;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                return myResponseStream;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将对象转换为URL参数格式,如:id=11111&name=www.cscode.net
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string GetUrlParam(Object instance)
        {
            StringBuilder sb = new StringBuilder("");
            PropertyInfo[] pi = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            object value = null;
            foreach (PropertyInfo p in pi)
            {
                value = p.GetValue(instance, null);
                if (sb.Length == 0)
                    sb.Append(p.Name + "=" + (value == null ? "" : value.ToString()));
                else
                    sb.Append("&" + p.Name + "=" + (value == null ? "" : value.ToString()));
            }
            return sb.ToString();
        }

    }
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
上一篇:CSFrameworkV5.1旗舰版 - 电子邮件附件文件介绍
下一篇:System.Web.HttpUtility 对URL/HTML字符串进行编码
评论列表

发表评论

评论内容
昵称:
关联文章

WebApiTools.cs - WebApi客户调用Web Api接口工具
基于Web前端用户调用CSFramework.WebApi服务登录登出接口实现
CSFramework.WebApi开发框架模拟Web用户登录、调用WebApi接口增删改查数据
Demo调用WebApi接口 - CSFramework.WebApi开发框架
CSFramework.WebApi服务器框架:客户调用WebApi接口方式(签名+Token令牌)
Web使用VUE调用WebApi接口实现用户登录及采用Token方式数据交互
C/S客户Winform窗体调用WebApi接口(C# 实例)
客户使用HTTPGET请求调用WebApi指定FromUri参数对象模型的接口
C#.NET WEBAPI 接口设计与调用
WebApi接口安全机制:API接口限流防止恶意访问 ThrottlingHandler消息处理机制
什么是Web Api? ASP.NET Web Api体系架构
WebApi框架Token身份认证,Api接口Token验证
客户测试程序(CS.WebApi.Tester)- CSFramework.WebApi框架
ASP.NET Web API入门介绍(一)
WCF开发框架-客户采用Certificate认证模式调用基于HTTPS协议的WCF接口
WCF开发框架-客户采用BASIC身份认证调用HTTPS协议WCF接口
WCF开发框架-客户采用Windows身份认证调用HTTPS协议WCF接口
Web开发框架-VUE使用Axios调用后台WebAPI接口
C#.NET 后WebApi接口搭建教程,WebApi接口开发实例
CSFramework.WebApi框架快速搭建后服务支持APP、B/S、C/S、微信小程序、公众号、Web客户