淘宝API系列(工具类)
淘宝API工具类:
1using System;
2using System.IO;
3using System.Net;
4using System.Text;
5using System.Collections;
6using System.Collections.Generic;
7
8
9namespace TaoBao.API.Common
10{
11 /// <summary>
12 /// WEB工具类
13 /// </summary>
14 public abstract class WebCommon
15 {
16 public static string DoPost(string pmUrl, IDictionary<string, string> 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<string, string> 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<string, string> pmTextParams, IDictionary<string, string> 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<string, string>> 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<string, string>> 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 }
106
107 reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
108 reqStream.Close();
109
110 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;
125
126 try
127 {
128 // 以字符流的方式读取HTTP响应
129 stream = rsp.GetResponseStream();
130 reader = new StreamReader(stream, encoding);
131
132 // 每次读取不大于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 finally
141 {
142 // 释放资源
143 if (reader != null) reader.Close();
144 if (stream != null) stream.Close();
145 if (rsp != null) rsp.Close();
146 }
147
148 return result.ToString();
149 }
150
151 /// <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;
159
160 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 }
170
171 return mimeType;
172 }
173
174 /// <summary>
175 /// 组装普通文本请求参数。
176 /// </summary>
177 /// <param name="parameters">Key-Value形式请求参数字典</param>
178 /// <returns>URL编码后的请求数据</returns>
179 private static string BuildPostData(IDictionary<string, string> parameters)
180 {
181 StringBuilder postData = new StringBuilder();
182 bool hasParam = false;
183
184 IEnumerator<KeyValuePair<string, string>> 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 }
196
197 postData.Append(name);
198 postData.Append("=");
199 postData.Append(Uri.EscapeDataString(value));
200 hasParam = true;
201 }
202 }
203
204 return postData.ToString();
205 }
206
207 }
208}
209
2using System.IO;
3using System.Net;
4using System.Text;
5using System.Collections;
6using System.Collections.Generic;
7
8
9namespace TaoBao.API.Common
10{
11 /// <summary>
12 /// WEB工具类
13 /// </summary>
14 public abstract class WebCommon
15 {
16 public static string DoPost(string pmUrl, IDictionary<string, string> 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<string, string> 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<string, string> pmTextParams, IDictionary<string, string> 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<string, string>> 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<string, string>> 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 }
106
107 reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
108 reqStream.Close();
109
110 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;
125
126 try
127 {
128 // 以字符流的方式读取HTTP响应
129 stream = rsp.GetResponseStream();
130 reader = new StreamReader(stream, encoding);
131
132 // 每次读取不大于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 finally
141 {
142 // 释放资源
143 if (reader != null) reader.Close();
144 if (stream != null) stream.Close();
145 if (rsp != null) rsp.Close();
146 }
147
148 return result.ToString();
149 }
150
151 /// <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;
159
160 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 }
170
171 return mimeType;
172 }
173
174 /// <summary>
175 /// 组装普通文本请求参数。
176 /// </summary>
177 /// <param name="parameters">Key-Value形式请求参数字典</param>
178 /// <returns>URL编码后的请求数据</returns>
179 private static string BuildPostData(IDictionary<string, string> parameters)
180 {
181 StringBuilder postData = new StringBuilder();
182 bool hasParam = false;
183
184 IEnumerator<KeyValuePair<string, string>> 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 }
196
197 postData.Append(name);
198 postData.Append("=");
199 postData.Append(Uri.EscapeDataString(value));
200 hasParam = true;
201 }
202 }
203
204 return postData.ToString();
205 }
206
207 }
208}
209
Code
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Xml;
6using System.Xml.Serialization;
7using System.IO;
8
9namespace 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<string, string> reValue = new Dictionary<string, string>();
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 }
100
101 /// <summary>
102 /// 将键值对集合转成字符串
103 /// </summary>
104 /// <param name="pmDictionary">键值对集合</param>
105 /// <returns>字符串</returns>
106 public static string GetParams(IDictionary<string, string> 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 }
121
122 }
123}
124
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Xml;
6using System.Xml.Serialization;
7using System.IO;
8
9namespace 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<string, string> reValue = new Dictionary<string, string>();
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 }
100
101 /// <summary>
102 /// 将键值对集合转成字符串
103 /// </summary>
104 /// <param name="pmDictionary">键值对集合</param>
105 /// <returns>字符串</returns>
106 public static string GetParams(IDictionary<string, string> 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 }
121
122 }
123}
124