client.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.Text;
  5. using System.IO;
  6. using System.Fire.Serialize;
  7. namespace System.Net.ApiService {
  8. public class client {
  9. protected const string DEFAULT_USER_AGENT = "BPClient/1.0";
  10. #region Json
  11. public static T Get_Json<T>(string Url, NameValueCollection Headers = null) {
  12. return Get_Json<T>(Url, Headers, null);
  13. }
  14. public static T Get_Json<T>(string Url, NameValueCollection Headers, NameValueCollection query) {
  15. try {
  16. HttpWebRequest request = CreateRequest(Url, Headers, query);
  17. request.Method = "GET";
  18. WebResponse response = request.GetResponse();
  19. return Read_Json<T>(response);
  20. } catch(Exception ex) {
  21. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, query));
  22. }
  23. return Read_Json<T>(null);
  24. }
  25. public static System.Text.Json.JsonDocument Get_Json(string Url, NameValueCollection Headers = null) {
  26. return Get_Json(Url, Headers, null);
  27. }
  28. public static System.Text.Json.JsonDocument Get_Json(string Url, NameValueCollection Headers, NameValueCollection query) {
  29. try {
  30. HttpWebRequest request = CreateRequest(Url, Headers, query);
  31. request.Method = "GET";
  32. WebResponse response = request.GetResponse();
  33. Stream data = response.GetResponseStream();
  34. StreamReader tr = new StreamReader(data);
  35. string raw = tr.ReadToEnd();
  36. return System.Text.Json.JsonDocument.Parse(raw);
  37. } catch(Exception ex) {
  38. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, query));
  39. return null;
  40. }
  41. }
  42. public static T Post_Json<T>(string Url, NameValueCollection Headers, NameValueCollection post) {
  43. return Post_Json<T>(Url, Headers, null, post);
  44. }
  45. public static System.Text.Json.JsonDocument Post_Json(string Url, NameValueCollection Headers, NameValueCollection post) {
  46. return Post_Json(Url, Headers, null, post);
  47. }
  48. public static T Post_Json<T>(string Url, NameValueCollection Headers, NameValueCollection query, NameValueCollection post) {
  49. HttpWebRequest request = CreateRequest(Url, Headers, query);
  50. string post_string = QueryString(post);
  51. /*if (post != null && post.Count > 0) {
  52. foreach (string key in query) {
  53. post_string += (post_string == "" ? "?" : "&") + UrlEncode(key) + "=" + UrlEncode(query[key]);
  54. }
  55. }*/
  56. byte[] content = System.Text.Encoding.ASCII.GetBytes(post_string);
  57. request.Method = "POST";
  58. request.ContentLength = content.Length;
  59. Stream dataStream = request.GetRequestStream();
  60. dataStream.Write(content, 0, content.Length);
  61. dataStream.Close();
  62. try {
  63. WebResponse response = request.GetResponse();
  64. return Read_Json<T>(response);
  65. } catch(Exception ex) {
  66. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, query, post));
  67. return Activator.CreateInstance<T>();
  68. }
  69. }
  70. public static System.Text.Json.JsonDocument Post_Json(string Url, NameValueCollection Headers, NameValueCollection query, NameValueCollection post) {
  71. HttpWebRequest request = CreateRequest(Url, Headers, query);
  72. string post_string = QueryString(post);
  73. /*if (post != null && post.Count > 0) {
  74. foreach (string key in post) {
  75. post_string += (post_string == "" ? "?" : "&") + UrlEncode(key) + "=" + UrlEncode(post[key]);
  76. }
  77. }*/
  78. byte[] content = System.Text.Encoding.ASCII.GetBytes(post_string);
  79. request.Method = "POST";
  80. request.ContentLength = content.Length;
  81. Stream dataStream = request.GetRequestStream();
  82. dataStream.Write(content, 0, content.Length);
  83. dataStream.Close();
  84. try {
  85. WebResponse response = request.GetResponse();
  86. Stream data = response.GetResponseStream();
  87. StreamReader tr = new StreamReader(data);
  88. string raw = tr.ReadToEnd();
  89. return System.Text.Json.JsonDocument.Parse(raw);
  90. } catch(Exception ex) {
  91. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, query, post));
  92. return null;
  93. }
  94. }
  95. protected static T Read_Json<T>(WebResponse response) {
  96. Stream data = response.GetResponseStream();
  97. StreamReader tr = new StreamReader(data);
  98. string raw = tr.ReadToEnd();
  99. return System.Text.Json.JsonSerializer.Deserialize<T>(raw);
  100. }
  101. #endregion
  102. #region Xml
  103. public static Xml.XmlDocument Get_Xml(string Url, NameValueCollection Headers = null) {
  104. try {
  105. HttpWebRequest request = CreateRequest(Url, Headers);
  106. request.Method = "GET";
  107. WebResponse response = request.GetResponse();
  108. return Read_Xml(response);
  109. } catch(Exception ex) {
  110. return null;
  111. }
  112. }
  113. public static Xml.XmlDocument Get_Xml(string Url, NameValueCollection Headers, NameValueCollection query) {
  114. try {
  115. HttpWebRequest request = CreateRequest(Url, Headers, query);
  116. request.Method = "GET";
  117. WebResponse response = request.GetResponse();
  118. return Read_Xml(response);
  119. } catch (Exception ex) {
  120. return null;
  121. }
  122. }
  123. public static Xml.XmlDocument Post_Xml(string Url, NameValueCollection Headers, NameValueCollection post) {
  124. return Post_Xml(Url, Headers, null, post);
  125. }
  126. public static Xml.XmlDocument Post_Xml(string Url, NameValueCollection Headers, NameValueCollection query, NameValueCollection post) {
  127. HttpWebRequest request = CreateRequest(Url, Headers, query);
  128. string post_string = QueryString(post);
  129. /*if (post != null && post.Count > 0) {
  130. foreach (string key in query) {
  131. post_string += (post_string == "" ? "?" : "&") + UrlEncode(key) + "=" + UrlEncode(query[key]);
  132. }
  133. }*/
  134. byte[] content = System.Text.Encoding.ASCII.GetBytes(post_string);
  135. request.Method = "POST";
  136. request.ContentLength = content.Length;
  137. Stream dataStream = request.GetRequestStream();
  138. dataStream.Write(content, 0, content.Length);
  139. dataStream.Close();
  140. WebResponse response = request.GetResponse();
  141. return Read_Xml(response);
  142. }
  143. protected static Xml.XmlDocument Read_Xml(WebResponse response) {
  144. Stream data = response.GetResponseStream();
  145. StreamReader tr = new StreamReader(data);
  146. string raw = tr.ReadToEnd();
  147. Xml.XmlDocument doc = new Xml.XmlDocument();
  148. doc.LoadXml(raw);
  149. return doc;
  150. }
  151. #endregion
  152. #region String
  153. public static string Get_String(string Url, NameValueCollection Headers = null) {
  154. HttpWebRequest request = CreateRequest(Url, Headers);
  155. request.Method = "GET";
  156. try {
  157. WebResponse response = request.GetResponse();
  158. return Read_String(response);
  159. } catch(Exception ex) {
  160. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, null, null));
  161. return GetClientErrorMessage(ex);
  162. }
  163. }
  164. public static string Get_String(string Url, NameValueCollection Headers, NameValueCollection query) {
  165. HttpWebRequest request = CreateRequest(Url, Headers, query);
  166. request.Method = "GET";
  167. try {
  168. WebResponse response = request.GetResponse();
  169. return Read_String(response);
  170. } catch(Exception ex) {
  171. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, query, null));
  172. return GetClientErrorMessage(ex, Url, Headers, query);
  173. }
  174. }
  175. public static string Post_String(string Url, NameValueCollection Headers, NameValueCollection post) {
  176. return Post_String(Url, Headers, null, post);
  177. }
  178. public static string Post_String(string Url, NameValueCollection Headers, NameValueCollection query, NameValueCollection post) {
  179. try {
  180. HttpWebRequest request = CreateRequest(Url, Headers, query);
  181. string post_string = QueryString(post);
  182. /*if (post != null && post.Count > 0) {
  183. foreach (string key in query) {
  184. post_string += (post_string == "" ? "?" : "&") + UrlEncode(key) + "=" + UrlEncode(query[key]);
  185. }
  186. }*/
  187. byte[] content = System.Text.Encoding.ASCII.GetBytes(post_string);
  188. request.Method = "POST";
  189. request.ContentLength = content.Length;
  190. Stream dataStream = request.GetRequestStream();
  191. dataStream.Write(content, 0, content.Length);
  192. dataStream.Close();
  193. WebResponse response = request.GetResponse();
  194. return Read_String(response);
  195. } catch(Exception ex) {
  196. System.Diagnostics.Debug.WriteLine(GetClientErrorMessage(ex, Url, Headers, query, post));
  197. return GetClientErrorMessage(ex, Url, Headers, query, post);
  198. }
  199. }
  200. protected static string Read_String(WebResponse response) {
  201. try {
  202. Stream data = response.GetResponseStream();
  203. StreamReader tr = new StreamReader(data);
  204. string raw = tr.ReadToEnd();
  205. return raw;
  206. } catch(Exception ex) {
  207. return GetClientErrorMessage(ex);
  208. }
  209. }
  210. #endregion
  211. #region Object
  212. public static T Get_Object<T>(string Url, NameValueCollection Headers = null) {
  213. string s = Get_String(Url, Headers);
  214. byte[] b = Convert.FromBase64String(s);
  215. MemoryStream mem = new MemoryStream(b);
  216. return Serializer.DeserializeObject<T>(mem);
  217. }
  218. public static T Get_Object<T>(string Url, NameValueCollection Headers, NameValueCollection query) {
  219. string s = Get_String(Url, Headers, query);
  220. byte[] b = Convert.FromBase64String(s);
  221. MemoryStream mem = new MemoryStream(b);
  222. return Serializer.DeserializeObject<T>(mem);
  223. }
  224. public static T Post_Object<T>(string Url, NameValueCollection Headers, NameValueCollection post) {
  225. string s = Post_String(Url, Headers, post);
  226. byte[] b = Convert.FromBase64String(s);
  227. MemoryStream mem = new MemoryStream(b);
  228. return Serializer.DeserializeObject<T>(mem);
  229. }
  230. public static T Post_Object<T>(string Url, NameValueCollection Headers, NameValueCollection post, NameValueCollection query) {
  231. string s = Post_String(Url, Headers, query, post);
  232. byte[] b = Convert.FromBase64String(s.Trim());
  233. MemoryStream mem = new MemoryStream(b);
  234. return Serializer.DeserializeObject<T>(mem);
  235. }
  236. #endregion
  237. protected static string GetClientErrorMessage() {
  238. return "Failed to connect";
  239. }
  240. protected static string GetClientErrorMessage(Exception ex, string Url, NameValueCollection Headers) {
  241. return "Url: "+ Url + "\n" + ex.Message + "\n" + ex.Source + "\n" + (ex.TargetSite == null ? "" : GetMethodName(ex.TargetSite) + "\n") + ex.StackTrace + (ex.InnerException != null ? "\n" + GetClientErrorMessage(ex.InnerException, 1) : "");
  242. }
  243. protected static string GetClientErrorMessage(Exception ex, string Url, NameValueCollection Headers, NameValueCollection query) {
  244. return "Url: " + Url + "\nQuery: " + QueryString(query) + "\n" + ex.Message + "\n" + ex.Source + "\n" + (ex.TargetSite == null ? "" : GetMethodName(ex.TargetSite) + "\n") + ex.StackTrace + (ex.InnerException != null ? "\n" + GetClientErrorMessage(ex.InnerException, 1) : "");
  245. }
  246. protected static string GetClientErrorMessage(Exception ex, string Url, NameValueCollection Headers, NameValueCollection query, NameValueCollection post) {
  247. return "Url: " + Url + "\nQuery: " + QueryString(query) + "\nPost: "+ QueryString(post) +"\nMessage: " + ex.Message + "\nSource: " + ex.Source + "\nTarget: " + (ex.TargetSite == null ? "" : GetMethodName(ex.TargetSite) + "\n") + "StackTrace: " + ex.StackTrace + (ex.InnerException != null ? "\n" + GetClientErrorMessage(ex.InnerException, 1) : "");
  248. }
  249. protected static string GetClientErrorMessage(Exception ex) {
  250. return "Message: " + ex.Message +
  251. "\nSource: " + ex.Source +
  252. "\nTargetSite: " + (ex.TargetSite == null ? "" : GetMethodName(ex.TargetSite)) +
  253. "\nStackTrace: " + ex.StackTrace +
  254. (ex.InnerException!=null?"\n"+GetClientErrorMessage(ex.InnerException,1):"");
  255. }
  256. protected static string GetClientErrorMessage(Exception ex, int deep) {
  257. return (new string(' ', deep * 2)) + "Message: " + ex.Message +
  258. "\n" + (new string(' ', deep * 2)) + "Source: " + ex.Source +
  259. "\n" + (new string(' ', deep * 2)) + "TargetSite: " + (ex.TargetSite == null ? "" : GetMethodName(ex.TargetSite)) +
  260. "\n" + (new string(' ', deep * 2)) + "Stack: " + ex.StackTrace +
  261. (ex.InnerException != null ? "\n" + GetClientErrorMessage(ex.InnerException, deep+1) : "");
  262. }
  263. protected static string GetMethodName(Reflection.MethodBase mi) {
  264. string res = "";
  265. if (mi.IsPublic) res += "public ";
  266. if (mi.IsPrivate) res += "private ";
  267. if (mi.IsFinal) res += "final ";
  268. if (mi.IsVirtual) res += "virtual ";
  269. if (mi.IsStatic) res += "static ";
  270. if (mi.Module != null)
  271. res += mi.Module.Name + "::";
  272. res += mi.Name;
  273. res += "(";
  274. Reflection.ParameterInfo[] pis = mi.GetParameters();
  275. bool bFirst = true;
  276. foreach (Reflection.ParameterInfo pi in pis) {
  277. if (bFirst) res += ", ";
  278. res += GetParameter(pi);
  279. bFirst = false;
  280. }
  281. res += ")";
  282. return res;
  283. }
  284. protected static string GetMethodName(Reflection.MethodInfo mi) {
  285. string res = "";
  286. if (mi.IsPublic) res += "public ";
  287. if (mi.IsPrivate) res += "private ";
  288. if (mi.IsFinal) res += "final ";
  289. if (mi.IsVirtual) res += "virtual ";
  290. if (mi.IsStatic) res += "static ";
  291. if (mi.ReturnType == null) res += "void ";
  292. else res += mi.ReturnType.Name+" ";
  293. if (mi.Module != null)
  294. res += mi.Module.Name + "::";
  295. res += mi.Name;
  296. res += "(";
  297. Reflection.ParameterInfo[] pis = mi.GetParameters();
  298. bool bFirst = true;
  299. foreach(Reflection.ParameterInfo pi in pis) {
  300. if (bFirst) res += ", ";
  301. res += GetParameter(pi);
  302. bFirst = false;
  303. }
  304. res += ")";
  305. return res;
  306. }
  307. protected static string GetParameter(Reflection.ParameterInfo pi) {
  308. string res="";
  309. res += "(";
  310. if (pi.IsOut) res += "out ";
  311. if (pi.IsIn) res += "in ";
  312. if (pi.IsOptional) res += "optional ";
  313. if (pi.IsRetval) res += "retval ";
  314. if (pi.IsLcid) res += "lcid ";
  315. res += pi.ParameterType.Name;
  316. res += ")";
  317. res += pi.Name;
  318. return res;
  319. }
  320. protected static string UrlEncode(string s) {
  321. return System.Net.WebUtility.UrlEncode(s);
  322. }
  323. protected static HttpWebRequest CreateRequest(string url, NameValueCollection Headers) {
  324. if (url.StartsWith("localhost"))
  325. url = "127.0.0.1" + url.Substring(9);
  326. string prefix = "";
  327. if (url.Contains(":")) {
  328. string protocol = url.Substring(0, url.IndexOf(':'));
  329. switch (protocol) {
  330. case "ftp":
  331. case "http":
  332. case "https":
  333. case "sftp":
  334. break;
  335. default:
  336. prefix = "http://";
  337. break;
  338. }
  339. } else {
  340. prefix = "http://";
  341. }
  342. System.Diagnostics.Debug.WriteLine("callUrl1: " + prefix + url);
  343. HttpWebRequest request = WebRequest.CreateHttp(prefix + url);
  344. if (Headers != null && Headers.Count > 0)
  345. request.Headers.Add(Headers);
  346. if (DEFAULT_USER_AGENT != "")
  347. request.Headers.Add(HttpRequestHeader.UserAgent, DEFAULT_USER_AGENT);
  348. request.Headers.Add(HttpRequestHeader.AcceptEncoding, "br, gzip");
  349. request.Headers.Add(HttpRequestHeader.Connection, "close");
  350. return request;
  351. }
  352. protected static HttpWebRequest CreateRequest(string url, NameValueCollection Headers, NameValueCollection query) {
  353. string query_string = QueryString(query);
  354. /*if (query != null && query.Count > 0) {
  355. foreach (string key in query) {
  356. query_string += (query_string == "" ? "?" : "&") + UrlEncode(key) + "=" + UrlEncode(query[key]);
  357. }
  358. }*/
  359. if (url.StartsWith("localhost"))
  360. url = "127.0.0.1" + url.Substring(9);
  361. string prefix = "";
  362. if(url.Contains(":")) {
  363. string protocol = url.Substring(0, url.IndexOf(':'));
  364. switch(protocol) {
  365. case "ftp":
  366. case "http":
  367. case "https":
  368. case "sftp":
  369. break;
  370. default:
  371. prefix = "http://";
  372. break;
  373. }
  374. } else {
  375. prefix = "http://";
  376. }
  377. string callUrl = prefix + url + query_string;
  378. System.Diagnostics.Debug.WriteLine("callUrl2: " + callUrl);
  379. HttpWebRequest request = WebRequest.CreateHttp(callUrl);
  380. if(Headers!=null && Headers.Count>0)
  381. request.Headers.Add(Headers);
  382. if (DEFAULT_USER_AGENT != "")
  383. request.Headers.Add(HttpRequestHeader.UserAgent, DEFAULT_USER_AGENT);
  384. request.Headers.Add(HttpRequestHeader.AcceptEncoding, "br, gzip");
  385. request.Headers.Add(HttpRequestHeader.Connection, "close");
  386. return request;
  387. }
  388. protected static string QueryString(NameValueCollection query) {
  389. string res = "";
  390. if (query == null || query.Count==0)
  391. return "";
  392. foreach (string key in query.AllKeys) {
  393. res += (res.Length==0 ? "?" : "&") + UrlEncode(key) + "=" + UrlEncode(query[key]);
  394. }
  395. return res;
  396. }
  397. protected static string QueryString(Dictionary<string,string> query) {
  398. string res = "";
  399. if (query == null || query.Count == 0)
  400. return "";
  401. foreach (KeyValuePair<string,string> itm in query) {
  402. res += (res.Length == 0 ? "?" : "&") + UrlEncode(itm.Key) + "=" + UrlEncode(itm.Value);
  403. }
  404. return res;
  405. }
  406. protected static string QueryString(Dictionary<string, object> query) {
  407. string res = "";
  408. if (query == null || query.Count == 0)
  409. return "";
  410. foreach (KeyValuePair<string, object> itm in query) {
  411. res += (res.Length == 0 ? "?" : "&") + UrlEncode(itm.Key) + "=" + UrlEncode(itm.Value.ToString());
  412. }
  413. return res;
  414. }
  415. protected static string HeaderString(NameValueCollection Headers) {
  416. return HeaderString(Headers, 0);
  417. }
  418. protected static string HeaderString(NameValueCollection Headers, int deep) {
  419. string res = "";
  420. if (Headers == null || Headers.Count == 0)
  421. return "";
  422. foreach (string key in Headers) {
  423. res += (res.Length==0?"":"\r\n") + (new string(' ', deep*2)) + key + ": " + Headers[key];
  424. }
  425. return res;
  426. }
  427. }
  428. }