淘宝API系列(工具类)

mac2022-06-30  90

淘宝API工具类:   1 using  System;   2 using  System.IO;   3 using  System.Net;   4 using  System.Text;   5 using  System.Collections;   6 using  System.Collections.Generic;   7   8   9 namespace  TaoBao.API.Common  10 { 11    /**//// <summary> 12    /// WEB工具类 13    /// </summary> 14    public abstract class WebCommon 15    { 16        public static string DoPost(string pmUrl, IDictionary<stringstring> pmParams) 17        { 18 19            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pmUrl); 20            req.Method = "POST"; 21            req.KeepAlive = true; 22            req.ContentType = "application/x-www-form-urlencoded"; 23 24            byte[] postData = Encoding.UTF8.GetBytes(BuildPostData(pmParams)); 25            Stream reqStream = req.GetRequestStream(); 26            reqStream.Write(postData, 0, postData.Length); 27            reqStream.Close(); 28 29            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); 30            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); 31            return GetResponseAsString(rsp, encoding); 32 33        } 34 35        public static string DoGet(string pmUrl, IDictionary<stringstring> pmParams) 36        { 37 38            if (pmParams != null && pmParams.Count > 0) 39            { 40                if (pmUrl.Contains("?")) 41                { 42                    pmUrl = pmUrl + "&" + BuildPostData(pmParams); 43                } 44                else 45                { 46                    pmUrl = pmUrl + "?" + BuildPostData(pmParams); 47                } 48            } 49 50            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pmUrl); 51            req.Method = "GET"; 52            req.KeepAlive = true; 53            req.ContentType = "application/x-www-form-urlencoded"; 54 55            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); 56            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); 57            return GetResponseAsString(rsp, encoding); 58 59        } 60        public static string DoPost(string pmUrl, IDictionary<stringstring> pmTextParams, IDictionary<stringstring> pmFileParams) { 61 62            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 63 64            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pmUrl); 65            req.Method = "POST"; 66            req.KeepAlive = true; 67            req.ContentType = "multipart/form-data;boundary=" + boundary; 68 69            Stream reqStream = req.GetRequestStream(); 70            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); 71            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); 72 73            // 组装文本请求参数 74            string entryTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}"; 75            IEnumerator<KeyValuePair<stringstring>> textEnum = pmTextParams.GetEnumerator(); 76            while (textEnum.MoveNext()) 77            { 78                string formItem = string.Format(entryTemplate, textEnum.Current.Key, textEnum.Current.Value); 79                byte[] itemBytes = Encoding.UTF8.GetBytes(formItem); 80                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); 81                reqStream.Write(itemBytes, 0, itemBytes.Length); 82            } 83 84            // 组装文件请求参数 85            string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n"; 86            IEnumerator<KeyValuePair<stringstring>> fileEnum = pmFileParams.GetEnumerator(); 87            while (fileEnum.MoveNext()) 88            { 89                string key = fileEnum.Current.Key; 90                string path = fileEnum.Current.Value; 91                string fileItem = string.Format(fileTemplate, key, path, GetMimeType(path)); 92                byte[] itemBytes = Encoding.UTF8.GetBytes(fileItem); 93                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); 94                reqStream.Write(itemBytes, 0, itemBytes.Length); 95 96                using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) 97                { 98                    byte[] buffer = new byte[1024]; 99                    int readBytes = 0;100                    while ((readBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)101                    {102                        reqStream.Write(buffer, 0, readBytes);103                    }104                }105            }106107            reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);108            reqStream.Close();109110            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();111            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);112            return GetResponseAsString(rsp, encoding);113        }114        /**//// <summary>115        /// 把响应流转换为文本。116        /// </summary>117        /// <param name="rsp">响应流对象</param>118        /// <param name="encoding">编码方式</param>119        /// <returns>响应文本</returns>120        private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)121        {122            StringBuilder result = new StringBuilder();123            Stream stream = null;124            StreamReader reader = null;125126            try127            {128                // 以字符流的方式读取HTTP响应129                stream = rsp.GetResponseStream();130                reader = new StreamReader(stream, encoding);131132                // 每次读取不大于512个字符,并写入字符串133                char[] buffer = new char[512];134                int readBytes = 0;135                while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)136                {137                    result.Append(buffer, 0, readBytes);138                }139            }140            finally141            {142                // 释放资源143                if (reader != null) reader.Close();144                if (stream != null) stream.Close();145                if (rsp != null) rsp.Close();146            }147148            return result.ToString();149        }150151        /**//// <summary>152        /// 根据文件名后缀获取图片型文件的Mime-Type。153        /// </summary>154        /// <param name="filePath">文件全名</param>155        /// <returns>图片文件的Mime-Type</returns>156        private static string GetMimeType(string filePath)157        {158            string mimeType;159160            switch (Path.GetExtension(filePath).ToLower())161            {162                case ".bmp": mimeType = "image/bmp"break;163                case ".gif": mimeType = "image/gif"break;164                case ".ico": mimeType = "image/x-icon"break;165                case ".jpeg": mimeType = "image/jpeg"break;166                case ".jpg": mimeType = "image/jpeg"break;167                case ".png": mimeType = "image/png"break;168                default: mimeType = "application/octet-stream"break;169            }170171            return mimeType;172        }173174        /**//// <summary>175        /// 组装普通文本请求参数。176        /// </summary>177        /// <param name="parameters">Key-Value形式请求参数字典</param>178        /// <returns>URL编码后的请求数据</returns>179        private static string BuildPostData(IDictionary<stringstring> parameters)180        {181            StringBuilder postData = new StringBuilder();182            bool hasParam = false;183184            IEnumerator<KeyValuePair<stringstring>> dem = parameters.GetEnumerator();185            while (dem.MoveNext())186            {187                string name = dem.Current.Key;188                string value = dem.Current.Value;189                // 忽略参数名或参数值为空的参数190                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))191                {192                    if (hasParam)193                    {194                        postData.Append("&");195                    }196197                    postData.Append(name);198                    postData.Append("=");199                    postData.Append(Uri.EscapeDataString(value));200                    hasParam = true;201                }202            }203204            return postData.ToString();205        }206207    }208} 209 Code using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Security.Cryptography;namespace TaoBao.API.Common{    /// <summary>    /// 签名    /// </summary>    public class EncryptUtil    {        /// <summary>生成有效签名</summary>        /// <param name="@params"></param>        /// <param name="secret"></param>        /// <returns></returns>        public static string Signature(System.Collections.Generic.IDictionary<stringstring            > @params, string secret, string signName)        {            string result = null;            if (@params == null)            {                return result;            }            // remove sign parameter                        @params.Remove(signName);            IDictionary<stringstring> treeMap = new SortedList<stringstring>();            //treeMap.PutAll(@params);            foreach (KeyValuePair<stringstring> kvp in @params)            {                treeMap.Add(kvp.Key, kvp.Value);            }            System.Collections.IEnumerator iter = @treeMap.Keys.GetEnumerator();            System.Text.StringBuilder orgin = new System.Text.StringBuilder(secret);            while (iter.MoveNext())            {                string name = (string)iter.Current;                string value = @treeMap[name];                orgin.Append(name).Append(value);            }            try            {                result = Md5Hex(orgin.ToString());            }            catch (System.Exception)            {                throw new System.Exception("sign error !");            }            return result;        }        /**/        /// <summary>        /// MD5加密并输出十六进制字符串        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static string Md5Hex(string str)        {            string dest = "";            //实例化一个md5对像            MD5 md5 = MD5.Create();            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择             byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得            for (int i = 0; i < s.Length; i++)            {                // 将得到的字符串使用十六进制类型格式。格式后的字符是大写的字母                if (s[i] < 16)                {                    dest = dest + "0" + s[i].ToString("X");                }                else                {                    dest = dest + s[i].ToString("X");                }            }            return dest;        }    }}   1 using  System;   2 using  System.Collections.Generic;   3 using  System.Linq;   4 using  System.Text;   5 using  System.Xml;   6 using  System.Xml.Serialization;   7 using  System.IO;   8   9 namespace  TaoBao.API.Common  10 { 11    /**//// <summary> 12    /// 操作XML常用方法集合 13    /// </summary> 14    public class XMLCommon 15    { 16 17        /**//// <summary> 18        /// 将XML文档转换成实例对象 19        /// </summary> 20        /// <typeparam name="T">对象类型</typeparam> 21        /// <param name="pmFileName">文件名</param> 22        /// <returns>实例对象</returns> 23        public static T DeserializeFile<T>(string pmFileName) 24        { 25            FileStream fs = new FileStream(pmFileName, FileMode.Open); 26            XmlSerializer xs = new XmlSerializer(typeof(T)); 27            T tObjext = (T)xs.Deserialize(fs); 28            fs.Close(); 29            fs.Dispose(); 30            return tObjext; 31        } 32 33        /**//// <summary> 34        /// 将实例对象写入XML文档 35        /// </summary> 36        /// <typeparam name="T">对象类型</typeparam> 37        /// <param name="pmFileName">文件名</param> 38        /// <param name="pmT">实例对象</param> 39        public static void SerializeFile<T>(string pmFileName, T pmT) 40        { 41 42            XmlSerializer serializer = new XmlSerializer(pmT.GetType()); 43            TextWriter writer = new StreamWriter(pmFileName); 44            serializer.Serialize(writer, pmT); 45            writer.Close(); 46        } 47  48 49        /**//// <summary> 50        /// 将XML字符串转换成对象 51        /// </summary> 52        /// <typeparam name="T">对象类型</typeparam> 53        /// <param name="pmXMLString">XML字符串</param> 54        /// <returns>实例对象</returns> 55        public static T DeserializeXML<T>(string pmXMLString) { 56 57            XmlSerializer xs = new XmlSerializer(typeof(T)); 58            T tObjext = (T)xs.Deserialize(new StringReader(pmXMLString)); 59            return tObjext; 60        } 61 62        /**//// <summary> 63        /// 将Josn字符串转换成对象 64        /// </summary> 65        /// <typeparam name="T">对象类型</typeparam> 66        /// <param name="pmXMLString">Josn字符串</param> 67        /// <returns>实例对象</returns> 68        public static T DeserializeJSON<T>(string pmXMLString) 69        { 70            XmlSerializer xs = new XmlSerializer(typeof(T)); 71            T tObjext = (T)xs.Deserialize(new StringReader(pmXMLString)); 72            return tObjext; 73        } 74 75 76        /**//// <summary> 77        /// 将实例对象转换成键值对集合 78        /// </summary> 79        /// <typeparam name="T">对象类型</typeparam> 80        /// <param name="pmT">实例对象</param> 81        /// <returns>键值对集合</returns> 82        public static Dictionary<string,string> DeserializeClass<T>(T pmT) 83        { 84            UTF8Encoding utf8 = new UTF8Encoding(); 85            Dictionary<stringstring> reValue = new Dictionary<stringstring>(); 86            string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff")+"xmlfile.xml"; 87            SerializeFile(filename, pmT); 88            FileStream fs = new FileStream(filename, FileMode.Open); 89            XmlDocument document = new XmlDocument(); 90            document.Load(fs); 91            foreach(XmlNode child in document.DocumentElement.ChildNodes){ 92 93                reValue.Add(child.Name, utf8.GetString(utf8.GetBytes(child.InnerText))); 94            } 95            fs.Close(); 96            fs.Dispose(); 97            //File.Delete(filename); 98            return reValue; 99        }100101        /**//// <summary>102        /// 将键值对集合转成字符串103        /// </summary>104        /// <param name="pmDictionary">键值对集合</param>105        /// <returns>字符串</returns>106        public static string GetParams(IDictionary<stringstring> pmDictionary)107        {108            System.Collections.IEnumerator iter = pmDictionary.Keys.GetEnumerator();109            System.Text.StringBuilder orgin = new System.Text.StringBuilder();110            int i = 0;111            while (iter.MoveNext())112            {113                string name = (string)iter.Current;114                string value =System.Web.HttpUtility.UrlEncode(pmDictionary[name], System.Text.Encoding.UTF8);115                orgin.Append(name).Append("=").Append(value);116                if (i != pmDictionary.Keys.Count - 1) orgin.Append("&");117                i++;118            }119            return orgin.ToString();120        }121122    }123} 124

转载于:https://www.cnblogs.com/bbqqqbq/archive/2009/08/20/1550947.html

相关资源:淘宝图片处理
最新回复(0)