C# 调用API接口处理公共类 自带JSON实体互转类

2020-12-13 04:11

阅读:607

标签:json反序列   json   json序列化   json序列化对象   api   

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace AirMedia.Wap.Core
{
    public static class HttpWebHelper
    {
        ///   
        /// httpwebrequest类中的一些属性的集合  
        ///   
        public class RequestParam
        {
            ///   
            /// 获取或设置request类中的Accept属性  
            /// 用以设置接受的文件类型  
            ///               
            public string Accept { get; set; }

            ///   
            /// 获取或设置request类中的ContentType属性  
            /// 用以设置请求的媒体类型  
            ///             
            public string ContentType { get; set; }

            ///   
            /// 获取或设置request类中的UserAgent属性  
            /// 用以设置请求的客户端信息  
            ///   
            public string UserAgent { get; set; }

            ///   
            /// 获取或设置request类中的Method属性  
            /// 可以将 Method 属性设置为任何 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。  
            /// 如果 ContentLength 属性被设置为 -1 以外的任何值,则必须将 Method 属性设置为上载数据的协议属性。  
            ///               
            public string Method { get; set; }

            /// 
            /// 发送的数据
            /// 
            public byte[] PostData { get; set; }
        }
        ///   
        /// 构建一个httt请求以获取目标链接的cookies,需要传入目标的登录地址和相关的post信息,返回完成登录的cookies,以及返回的html内容  
        ///   
        /// 登录页面的地址  
        /// post信息  
        /// 输出的html代码  
        /// 请求的标头所需要的相关属性设置  
        /// 请求完成后的cookies  
        public static CookieCollection GetCookie(string url, RequestParam rppt, out string strHtml)
        {

            CookieCollection ckclReturn = new CookieCollection();
            CookieContainer cc = new CookieContainer();
            HttpWebRequest hwRequest;
            HttpWebResponse hwResponse;
            Stream stream;

            hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            hwRequest.CookieContainer = cc;
            if (rppt != null)
            {
                hwRequest.Accept = rppt.Accept;
                hwRequest.ContentType = rppt.ContentType;
                hwRequest.UserAgent = rppt.UserAgent;
                hwRequest.Method = rppt.Method;
                hwRequest.ContentLength = rppt.PostData.Length;
                //写入标头  

                stream = hwRequest.GetRequestStream();
                stream.Write(rppt.PostData, 0, rppt.PostData.Length);
                stream.Close();
            }
            //发送请求获取响应内容  
            try
            {
                hwResponse = (HttpWebResponse)hwRequest.GetResponse();
            }
            catch
            {
                strHtml = "";
                return ckclReturn;
            }
            stream = hwResponse.GetResponseStream();
            StreamReader sReader = new StreamReader(stream, Encoding.UTF8);
            strHtml = sReader.ReadToEnd();
            sReader.Close();
            stream.Close();
            //获取缓存内容  
            ckclReturn = hwResponse.Cookies;
            return ckclReturn;
        }

        ///   
        /// 根据已经获取的有效cookies来获取目标链接的内容  
        ///   
        /// 目标链接的url  
        ///post的byte信息  
        /// 已经获取到的有效cookies  
        /// 头属性的相关设置  
        /// 目标连接的纯文本:"txt/html"  
        public static string GetHtmlByCookies(string strUri, byte[] post, CookieCollection ccl, RequestParam rppt)
        {
            CookieContainer cc = new CookieContainer();
            HttpWebRequest hwRequest;
            HttpWebResponse hwResponse;

            //构建即将发送的包头         
            hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(strUri));
            cc.Add(ccl);
            hwRequest.CookieContainer = cc;
            hwRequest.Accept = rppt.Accept;
            hwRequest.ContentType = rppt.ContentType;
            hwRequest.UserAgent = rppt.UserAgent;
            hwRequest.Method = rppt.Method;
            hwRequest.ContentLength = post.Length;
            //写入post信息  
            Stream stream;
            stream = hwRequest.GetRequestStream();
            stream.Write(post, 0, post.Length);
            stream.Close();
            //发送请求获取响应内容  
            try
            {
                hwResponse = (HttpWebResponse)hwRequest.GetResponse();
            }
            catch
            {
                return "";
            }

            stream = hwResponse.GetResponseStream();
            StreamReader sReader = new StreamReader(stream, Encoding.Default);
            string strHtml = sReader.ReadToEnd();
            sReader.Close();
            stream.Close();

            //返回值            
            return strHtml;
        }


        ///   
        /// 根据泛型来构建字符串用于post  
        ///   
        /// 带有键值对的泛型  
        /// 构建完毕的字符串  
        public static byte[] CreatePostData(Dictionary dir)
        {
            StringBuilder strPost = new StringBuilder();
            foreach (KeyValuePair kvp in dir)
            {
                strPost.Append(kvp.Key);
                strPost.Append('=');
                if (!string.IsNullOrWhiteSpace(kvp.Value))
                {
                    strPost.Append(System.Web.HttpUtility.UrlEncode(kvp.Value));
                }
                strPost.Append('&');
            }
            return CreatePostData(strPost.ToString().TrimEnd('&'));
        }

        public static byte[] CreatePostData(string input)
        {
            return Encoding.Default.GetBytes(input);
        }

        /// 
        /// 向指定uri发起GET请求
        /// 
        /// 
        /// 
        /// 
        public static string GET(string url)
        {
            WebClient wc = new WebClient();
            wc.Encoding = System.Text.Encoding.UTF8;
            string s = wc.DownloadString(url);
            s = HttpUtility.UrlDecode(s);
            return s;
        }
    }

    ///   
    /// 有关HTTP请求的辅助类  
    ///   
    public class HttpWebResponseUtility
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        ///   
        /// 创建GET方式的HTTP请求  
        ///   
        /// 请求的URL  
        /// 请求的超时时间  
        /// 请求的客户端浏览器信息,可以为空  
        /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空  
        ///   
        public static HttpWebResponse CreateGetHttpResponse(string url, IDictionary parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            StringBuilder buffer = new StringBuilder();
            if (!(parameters == null || parameters.Count == 0))
            {

                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
            }

            if (buffer.Length > 1)
            {
                url = url + "?" + buffer.ToString();
            }
            url = HttpUtility.UrlDecode(url);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = DefaultUserAgent;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            return request.GetResponse() as HttpWebResponse;
        }
        ///   
        /// 创建POST方式的HTTP请求  
        ///   
        /// 请求的URL  
        /// 随同请求POST的参数名称及参数值字典  
        /// 请求的超时时间  
        /// 请求的客户端浏览器信息,可以为空  
        /// 发送HTTP请求时所用的编码  
        /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空  
        ///   
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            // request.ContentType = "application/x-www-form-urlencoded";
            request.ContentType = "application/json";
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }

            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //如果需要POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        public static string PostXml(string url, string xml)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(xml);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "text/xml";
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode != HttpStatusCode.OK)
            {
                string message = String.Format("POST failed. Received HTTP {0}",
                response.StatusCode);
                throw new ApplicationException(message);
            }
            System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            string res = sr.ReadToEnd();
            sr.Close();
            response.Close();
            return res;
        }
    }
}


调用

string requestUrl = CoreInterface.ApiDomain + "api/Login/AddQRLog?grid={0}&ad={1}&grName={2}&vc={3}&br={4}&sc={5}&ts={6}&ps={7}";
            requestUrl = string.Format(requestUrl, grid, ad, grName, vc, br, sc, ts, ps);
            string resultJson = "";
            //try
            //{
                HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(requestUrl, null, 1000000, "", null, null);
                System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
                resultJson = sr.ReadToEnd();
                sr.Close();
            //}
            //catch (Exception)
            //{
            //    return RedirectToAction("Index", "Error");
            //}


 

C# 自带JSON转换类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;

namespace AirMedia.Wap.Core
{
    public static class JsonHelper
    {
        #region DataContractJsonSerializer

        /// 
        /// 对象转换成json
        /// 
        /// 
        /// 需要格式化的对象
        /// Json字符串
        public static string DataContractJsonSerialize(T jsonObject)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string json = null;
            using (MemoryStream ms = new MemoryStream()) //定义一个stream用来存发序列化之后的内容
            {
                serializer.WriteObject(ms, jsonObject);
                json = Encoding.UTF8.GetString(ms.GetBuffer()); //将stream读取成一个字符串形式的数据,并且返回
                ms.Close();
            }
            return json;
        }

        /// 
        /// json字符串转换成对象
        /// 
        /// 
        /// 要转换成对象的json字符串
        /// 
        public static T DataContractJsonDeserialize(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }
            return obj;
        }

        #endregion
    }
}


 

C# 调用API接口处理公共类 自带JSON实体互转类,搜素材,soscw.com

C# 调用API接口处理公共类 自带JSON实体互转类

标签:json反序列   json   json序列化   json序列化对象   api   

原文地址:http://blog.csdn.net/qq873113580/article/details/37591643


评论


亲,登录后才可以留言!