httpClient调用方式

  1. namespace SOA.Common
  2. {
  3. //httpClient调用WebApi
  4. public class HttpClientHelper
  5. {
  6. public static string GetHttpClient(string serverUrl, string method, WebHeaderCollection header)
  7. {
  8. using (HttpClient client = new HttpClient())
  9. {
  10. //如果有Basic认证的情况下,请自己封装header
  11. if (header != null)
  12. client.DefaultRequestHeaders.Add("Authorization", "BasicAuth " + header["Authorization"]);
  13. var response = client.GetAsync(serverUrl + method).Result; //拿到异步结果
  14. Console.WriteLine(response.StatusCode); //确保http成功
  15. return response.Content.ReadAsStringAsync().Result;
  16. }
  17. }
  18. public static string PostHttpClient(string serverUrl, string method, Dictionary<string, string> param)
  19. {
  20. using (HttpClient client = new HttpClient())
  21. {
  22. var content = new FormUrlEncodedContent(param);
  23. client.DefaultRequestHeaders.Add("user-agent",
  24. "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
  25. var response = client.PostAsync(serverUrl + method, content).Result; //拿到异步结果
  26. Console.WriteLine(response.StatusCode); //确保http成功
  27. return response.Content.ReadAsStringAsync().Result;
  28. }
  29. }
  30. /// <summary>
  31. /// httpClient使用代理
  32. /// </summary>
  33. /// <param name="serverUrl"></param>
  34. /// <param name="method"></param>
  35. /// <param name="param"></param>
  36. /// <returns></returns>
  37. public static string PostHttpClientWithProxy(string serverUrl, string method, Dictionary<string, string> param,
  38. ProxyParam proxyParam)
  39. {
  40. HttpClientHandler aHandler = new HttpClientHandler();
  41. aHandler.UseCookies = true;
  42. aHandler.AllowAutoRedirect = true;
  43. IWebProxy Proxya = new WebProxy(proxyParam.IP + ":" + proxyParam.Port);
  44. Proxya.Credentials = new NetworkCredential(proxyParam.Name, proxyParam.Pass, proxyParam.Domain);
  45. aHandler.Proxy = Proxya;
  46. using (HttpClient client = new HttpClient(aHandler))
  47. {
  48. var content = new FormUrlEncodedContent(param);
  49. client.DefaultRequestHeaders.Add("user-agent",
  50. "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
  51. var response = client.PostAsync(serverUrl + method, content).Result; //拿到异步结果
  52. Console.WriteLine(response.StatusCode); //确保http成功
  53. return response.Content.ReadAsStringAsync().Result;
  54. }
  55. }
  56. }
  57. public class ProxyParam
  58. {
  59. public string IP { get; set; }
  60. public string Port { get; set; }
  61. public string Name { get; set; }
  62. public string Pass { get; set; }
  63. public string Domain { get; set; }
  64. }
  65. }

httpWebReqeust调用方式(一般使用)

  1. //WebRequest调用WebApi
  2. public class WebRequestHelper
  3. {
  4. /// <summary>
  5. /// WebRequest的 Get 请求
  6. /// </summary>
  7. /// <param name="serverUrl" type="string">
  8. /// <para>
  9. /// api地址(地址+方法)
  10. /// </para>
  11. /// </param>
  12. /// <param name="paramData" type="string">
  13. /// <para>
  14. /// 参数
  15. /// </para>
  16. /// </param>
  17. public static string GetWebRequest(string serverUrl, string paramData, WebHeaderCollection header)
  18. {
  19. string requestUrl = serverUrl;
  20. if (serverUrl.IndexOf('?') == -1 && paramData.IndexOf('?') == -1)
  21. requestUrl += "?";
  22. requestUrl += paramData;
  23. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
  24. if (header != null)
  25. request.Headers = header;
  26. request.ContentType = "application/json";
  27. request.Timeout = 30 * 1000;
  28. request.Method = "GET";
  29. string result = string.Empty;
  30. using (var res = request.GetResponse() as HttpWebResponse)
  31. {
  32. if (res.StatusCode == HttpStatusCode.OK)
  33. {
  34. var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
  35. result = reader.ReadToEnd();
  36. }
  37. return result;
  38. }
  39. }
  40. /// <summary>
  41. /// WebRequest的 Post 请求
  42. /// </summary>
  43. /// <param name="serverUrl" type="string">
  44. /// <para>
  45. /// api地址(地址+方法)
  46. /// </para>
  47. /// </param>
  48. /// <param name="postData" type="string">
  49. /// <para>
  50. /// 参数
  51. /// </para>
  52. /// </param>
  53. public static string PostWebRequest(string serverUrl, string postData, WebHeaderCollection header)
  54. {
  55. var dataArray = Encoding.UTF8.GetBytes(postData);
  56. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);
  57. if (header != null)
  58. request.Headers = header;
  59. request.ContentLength = dataArray.Length;
  60. //设置上传服务的数据格式
  61. request.ContentType = "application/json";
  62. request.Timeout = 30 * 1000;
  63. request.Method = "POST";
  64. //创建输入流
  65. Stream dataStream;
  66. try
  67. {
  68. dataStream = request.GetRequestStream();
  69. }
  70. catch (Exception)
  71. {
  72. return null;//连接服务器失败
  73. }
  74. //发送请求
  75. dataStream.Write(dataArray, 0, dataArray.Length);
  76. dataStream.Close();
  77. //读取返回值
  78. string result = string.Empty;
  79. using (var res = request.GetResponse() as HttpWebResponse)
  80. {
  81. if (res.StatusCode == HttpStatusCode.OK)
  82. {
  83. var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
  84. result = reader.ReadToEnd();
  85. }
  86. return result;
  87. }
  88. }
  89. }

封装的调用

  1. namespace SOA.Common
  2. {
  3. public class ApiHelper
  4. {
  5. public static readonly ApiHelper Instance = new ApiHelper();
  6. public string RequestApi(string method, string queryString, WebHeaderCollection header = null)
  7. {
  8. string result = WebRequestHelper.GetWebRequest(ConfigHelper.Config.ApiUrl + method, queryString, header);
  9. return result;
  10. }
  11. public AjaxResult RequestApi<T>(string method, string queryString, WebHeaderCollection header = null)
  12. {
  13. var result = WebRequestHelper.GetWebRequest(ConfigHelper.Config.ApiUrl + method, queryString, header);
  14. return SerializeResult<T>(result);
  15. }
  16. /// <summary>
  17. /// 序列化结果
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="result"></param>
  21. /// <returns></returns>
  22. private AjaxResult SerializeResult<T>(string result)
  23. {
  24. AjaxResult resultModel = JsonConverter.FromJsonTo<AjaxResult>(result);
  25. if (resultModel.Status == 0 && resultModel.Data != null && !string.IsNullOrEmpty(resultModel.Data.ToString()))
  26. {
  27. if (resultModel.Data.ToString().IndexOf("[") == 0 && StringHelper.IsJson(resultModel.Data.ToString()))
  28. {
  29. resultModel.Data = JsonConverter.FromJsonTo<List<T>>(resultModel.Data.ToString());
  30. }
  31. else if (StringHelper.IsJson(resultModel.Data.ToString()))
  32. {
  33. resultModel.Data = JsonConverter.FromJsonTo<T>(resultModel.Data.ToString());
  34. }
  35. }
  36. return resultModel;
  37. }
  38. }
  39. }

StringHelper.cs 帮助类

  1. namespace SOA.Common
  2. {
  3. public class StringHelper
  4. {
  5. public static string AreaAttr(string defaultStr, int max = 0, string tipTitle = "", string tipid = "")
  6. {
  7. string text = "";
  8. if (!string.IsNullOrWhiteSpace(defaultStr))
  9. {
  10. text = text + " tipmsg=\"" + defaultStr + "\" onfocus=\"utils.ContentKeyFocus(this)\" onblur=\"utils.ContentKeyBlur(this)\"";
  11. text += " style=\"color:#999;\"";
  12. }
  13. if (max > 0)
  14. {
  15. string text2 = text;
  16. text = string.Concat(new string[]
  17. {
  18. text2,
  19. " onkeyup=\"utils.ContentKeyUpDown2(this,",
  20. max.ToString(),
  21. ",'",
  22. tipid,
  23. "',0,'",
  24. tipTitle,
  25. "')\""
  26. });
  27. }
  28. return text;
  29. }
  30. public static string InputAttr(string val, string defaultStr, int max = 0, string tipTitle = "", string tipid = "")
  31. {
  32. string text = "";
  33. if (!string.IsNullOrWhiteSpace(val))
  34. {
  35. text = text + " value=\"" + val + "\"";
  36. }
  37. if (!string.IsNullOrWhiteSpace(defaultStr))
  38. {
  39. if (string.IsNullOrWhiteSpace(val))
  40. {
  41. text = text + " value=\"" + defaultStr + "\"";
  42. }
  43. text = text + " tipmsg=\"" + defaultStr + "\" onfocus=\"utils.ContentKeyFocus(this)\" onblur=\"utils.ContentKeyBlur(this)\"";
  44. text += " style=\"color:#999;\"";
  45. }
  46. if (max > 0)
  47. {
  48. string text2 = text;
  49. text = string.Concat(new string[]
  50. {
  51. text2,
  52. " onkeyup=\"utils.ContentKeyUpDown2(this,",
  53. max.ToString(),
  54. ",'",
  55. tipid,
  56. "',0,'",
  57. tipTitle,
  58. "')\""
  59. });
  60. }
  61. return text;
  62. }
  63. public static string WapEncode(string source)
  64. {
  65. return (!string.IsNullOrEmpty(source)) ? source.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("‘", "&apos;").Replace("\"", "&quot;").Replace("$", "$").Replace(" ", "&nbsp;") : "";
  66. }
  67. public static string SubStr(string srcStr, int len)
  68. {
  69. string result;
  70. if (len < 1)
  71. {
  72. result = string.Empty;
  73. }
  74. else
  75. {
  76. if (string.IsNullOrEmpty(srcStr))
  77. {
  78. result = srcStr;
  79. }
  80. else
  81. {
  82. int byteCount = System.Text.Encoding.Default.GetByteCount(srcStr);
  83. if (byteCount <= len)
  84. {
  85. result = srcStr;
  86. }
  87. else
  88. {
  89. int num = 0;
  90. int num2 = 0;
  91. char[] array = srcStr.ToCharArray();
  92. char[] array2 = array;
  93. for (int i = 0; i < array2.Length; i++)
  94. {
  95. char c = array2[i];
  96. int byteCount2 = System.Text.Encoding.Default.GetByteCount(array, num2, 1);
  97. int num3 = num + byteCount2;
  98. if (num3 > len)
  99. {
  100. result = srcStr.Substring(0, num2) + "...";
  101. return result;
  102. }
  103. num = num3;
  104. num2++;
  105. }
  106. result = srcStr;
  107. }
  108. }
  109. }
  110. return result;
  111. }
  112. public static string ReplaceIDS(string oldIds, bool isNoZero = true)
  113. {
  114. string result;
  115. if (string.IsNullOrWhiteSpace(oldIds))
  116. {
  117. result = "";
  118. }
  119. else
  120. {
  121. string[] array = oldIds.Trim().Trim(new char[]
  122. {
  123. ','
  124. }).Split(new char[]
  125. {
  126. ','
  127. });
  128. System.Collections.Generic.List<long> list = new System.Collections.Generic.List<long>();
  129. string[] array2 = array;
  130. for (int i = 0; i < array2.Length; i++)
  131. {
  132. string text = array2[i];
  133. long num = TypeHelper.StrToInt64(text.Trim(), 0L);
  134. if (!isNoZero || num != 0L)
  135. {
  136. if (!list.Contains(num))
  137. {
  138. list.Add(num);
  139. }
  140. }
  141. }
  142. string text2 = "";
  143. foreach (long current in list)
  144. {
  145. text2 = text2 + "," + current.ToString();
  146. }
  147. result = text2.Trim(new char[]
  148. {
  149. ','
  150. });
  151. }
  152. return result;
  153. }
  154. public static string ReplaceStr2(string sourceStr)
  155. {
  156. string result;
  157. if (string.IsNullOrWhiteSpace(sourceStr))
  158. {
  159. result = sourceStr;
  160. }
  161. else
  162. {
  163. result = sourceStr.Trim().Replace(" ", "").Replace("'", "").Replace("\"", "");
  164. }
  165. return result;
  166. }
  167. public static string Cut(string str, int len, System.Text.Encoding encoding)
  168. {
  169. string result;
  170. if (string.IsNullOrEmpty(str))
  171. {
  172. result = str;
  173. }
  174. else
  175. {
  176. if (len <= 0)
  177. {
  178. result = string.Empty;
  179. }
  180. else
  181. {
  182. int byteCount = encoding.GetByteCount(str);
  183. if (byteCount > len)
  184. {
  185. bool flag = byteCount == str.Length;
  186. if (flag)
  187. {
  188. result = str.Substring(0, len);
  189. return result;
  190. }
  191. int num = 0;
  192. int num2 = 0;
  193. char[] array = str.ToCharArray();
  194. char[] array2 = array;
  195. for (int i = 0; i < array2.Length; i++)
  196. {
  197. char c = array2[i];
  198. int byteCount2 = encoding.GetByteCount(array, num2, 1);
  199. int num3 = num + byteCount2;
  200. if (num3 > len)
  201. {
  202. result = str.Substring(0, num2);
  203. return result;
  204. }
  205. num = num3;
  206. num2++;
  207. }
  208. }
  209. result = str;
  210. }
  211. }
  212. return result;
  213. }
  214. public static int GetChineseLength(string s)
  215. {
  216. int result;
  217. if (string.IsNullOrEmpty(s))
  218. {
  219. result = 0;
  220. }
  221. else
  222. {
  223. result = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(s);
  224. }
  225. return result;
  226. }
  227. public static int GetUTF8Length(string s)
  228. {
  229. int result;
  230. if (string.IsNullOrEmpty(s))
  231. {
  232. result = 0;
  233. }
  234. else
  235. {
  236. result = System.Text.Encoding.UTF8.GetByteCount(s);
  237. }
  238. return result;
  239. }
  240. public static string StrFormat(string str)
  241. {
  242. string result;
  243. if (str == null)
  244. {
  245. result = "";
  246. }
  247. else
  248. {
  249. str = str.Replace("\r\n", "<br />");
  250. str = str.Replace("\n", "<br />");
  251. result = str;
  252. }
  253. return result;
  254. }
  255. public static string EncodeHtml(string strHtml)
  256. {
  257. string result;
  258. if (strHtml != "")
  259. {
  260. strHtml = strHtml.Replace(",", "&def");
  261. strHtml = strHtml.Replace("'", "&dot");
  262. strHtml = strHtml.Replace(";", "&dec");
  263. result = strHtml;
  264. }
  265. else
  266. {
  267. result = "";
  268. }
  269. return result;
  270. }
  271. public static string HtmlDecode(string str)
  272. {
  273. return HttpUtility.HtmlDecode(str);
  274. }
  275. public static string HtmlEncode(string str)
  276. {
  277. return HttpUtility.HtmlEncode(str);
  278. }
  279. public static string UrlEncode(string str)
  280. {
  281. return HttpUtility.UrlEncode(str);
  282. }
  283. public static string UrlDecode(string str)
  284. {
  285. return HttpUtility.UrlDecode(str);
  286. }
  287. public static bool StrIsNullOrEmpty(string str)
  288. {
  289. return str == null || str.Trim() == string.Empty;
  290. }
  291. public static string CutString(string str, int startIndex, int length)
  292. {
  293. string result;
  294. if (string.IsNullOrWhiteSpace(str))
  295. {
  296. result = "";
  297. }
  298. else
  299. {
  300. if (startIndex >= 0)
  301. {
  302. if (length < 0)
  303. {
  304. length *= -1;
  305. if (startIndex - length < 0)
  306. {
  307. length = startIndex;
  308. startIndex = 0;
  309. }
  310. else
  311. {
  312. startIndex -= length;
  313. }
  314. }
  315. if (startIndex > str.Length)
  316. {
  317. result = "";
  318. return result;
  319. }
  320. }
  321. else
  322. {
  323. if (length < 0)
  324. {
  325. result = "";
  326. return result;
  327. }
  328. if (length + startIndex <= 0)
  329. {
  330. result = "";
  331. return result;
  332. }
  333. length += startIndex;
  334. startIndex = 0;
  335. }
  336. if (str.Length - startIndex < length)
  337. {
  338. length = str.Length - startIndex;
  339. }
  340. result = str.Substring(startIndex, length);
  341. }
  342. return result;
  343. }
  344. public static string CutString(string str, int startIndex)
  345. {
  346. string result;
  347. if (string.IsNullOrWhiteSpace(str))
  348. {
  349. result = "";
  350. }
  351. else
  352. {
  353. result = StringHelper.CutString(str, startIndex, str.Length);
  354. }
  355. return result;
  356. }
  357. public static string ToSqlInStr(System.Collections.Generic.List<int> ids)
  358. {
  359. string text = "";
  360. if (ids != null && ids.Count > 0)
  361. {
  362. foreach (int current in ids)
  363. {
  364. text = text + current + ",";
  365. }
  366. }
  367. text = text.Trim(",".ToCharArray());
  368. return text;
  369. }
  370. public static string ToSqlInStr(System.Collections.Generic.List<long> ids)
  371. {
  372. string text = "";
  373. if (ids != null && ids.Count > 0)
  374. {
  375. foreach (long current in ids)
  376. {
  377. text = text + current + ",";
  378. }
  379. }
  380. text = text.Trim(",".ToCharArray());
  381. return text;
  382. }
  383. public static string ToSqlInStr(System.Collections.Generic.List<string> ids)
  384. {
  385. string text = "";
  386. if (ids != null && ids.Count > 0)
  387. {
  388. foreach (string current in ids)
  389. {
  390. text = text + "'" + current + "',";
  391. }
  392. }
  393. text = text.Trim(",".ToCharArray());
  394. return text;
  395. }
  396. public static string FilteSQLStr(string Str)
  397. {
  398. string result;
  399. if (string.IsNullOrEmpty(Str))
  400. {
  401. result = "";
  402. }
  403. else
  404. {
  405. Str = Str.Replace("'", "");
  406. Str = Str.Replace("\"", "");
  407. Str = Str.Replace("&", "&amp");
  408. Str = Str.Replace("<", "&lt");
  409. Str = Str.Replace(">", "&gt");
  410. Str = Str.Replace("delete", "");
  411. Str = Str.Replace("update", "");
  412. Str = Str.Replace("insert", "");
  413. result = Str;
  414. }
  415. return result;
  416. }
  417. private static bool IsJsonStart(ref string json)
  418. {
  419. if (!string.IsNullOrEmpty(json))
  420. {
  421. json = json.Trim('\r', '\n', ' ');
  422. if (json.Length > 1)
  423. {
  424. char s = json[0];
  425. char e = json[json.Length - 1];
  426. return (s == '{' && e == '}') || (s == '[' && e == ']');
  427. }
  428. }
  429. return false;
  430. }
  431. internal static bool IsJson(string json)
  432. {
  433. int errIndex;
  434. return IsJson(json, out errIndex);
  435. }
  436. internal static bool IsJson(string json, out int errIndex)
  437. {
  438. errIndex = 0;
  439. if (IsJsonStart(ref json))
  440. {
  441. CharState cs = new CharState();
  442. char c;
  443. for (int i = 0; i < json.Length; i++)
  444. {
  445. c = json[i];
  446. if (SetCharState(c, ref cs) && cs.childrenStart)//设置关键符号状态。
  447. {
  448. string item = json.Substring(i);
  449. int err;
  450. int length = GetValueLength(item, true, out err);
  451. cs.childrenStart = false;
  452. if (err > 0)
  453. {
  454. errIndex = i + err;
  455. return false;
  456. }
  457. i = i + length - 1;
  458. }
  459. if (cs.isError)
  460. {
  461. errIndex = i;
  462. return false;
  463. }
  464. }
  465. return !cs.arrayStart && !cs.jsonStart;
  466. }
  467. return false;
  468. }
  469. /// <summary>
  470. /// 获取值的长度(当Json值嵌套以"{"或"["开头时)
  471. /// </summary>
  472. private static int GetValueLength(string json, bool breakOnErr, out int errIndex)
  473. {
  474. errIndex = 0;
  475. int len = 0;
  476. if (!string.IsNullOrEmpty(json))
  477. {
  478. CharState cs = new CharState();
  479. char c;
  480. for (int i = 0; i < json.Length; i++)
  481. {
  482. c = json[i];
  483. if (!SetCharState(c, ref cs))//设置关键符号状态。
  484. {
  485. if (!cs.jsonStart && !cs.arrayStart)//json结束,又不是数组,则退出。
  486. {
  487. break;
  488. }
  489. }
  490. else if (cs.childrenStart)//正常字符,值状态下。
  491. {
  492. int length = GetValueLength(json.Substring(i), breakOnErr, out errIndex);//递归子值,返回一个长度。。。
  493. cs.childrenStart = false;
  494. cs.valueStart = 0;
  495. //cs.state = 0;
  496. i = i + length - 1;
  497. }
  498. if (breakOnErr && cs.isError)
  499. {
  500. errIndex = i;
  501. return i;
  502. }
  503. if (!cs.jsonStart && !cs.arrayStart)//记录当前结束位置。
  504. {
  505. len = i + 1;//长度比索引+1
  506. break;
  507. }
  508. }
  509. }
  510. return len;
  511. }
  512. /// <summary>
  513. /// 字符状态
  514. /// </summary>
  515. private class CharState
  516. {
  517. internal bool jsonStart = false;//以 "{"开始了...
  518. internal bool setDicValue = false;// 可以设置字典值了。
  519. internal bool escapeChar = false;//以"\"转义符号开始了
  520. /// <summary>
  521. /// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。
  522. /// </summary>
  523. internal bool arrayStart = false;//以"[" 符号开始了
  524. internal bool childrenStart = false;//子级嵌套开始了。
  525. /// <summary>
  526. /// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】
  527. /// </summary>
  528. internal int state = 0;
  529. /// <summary>
  530. /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】
  531. /// </summary>
  532. internal int keyStart = 0;
  533. /// <summary>
  534. /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】
  535. /// </summary>
  536. internal int valueStart = 0;
  537. internal bool isError = false;//是否语法错误。
  538. internal void CheckIsError(char c)//只当成一级处理(因为GetLength会递归到每一个子项处理)
  539. {
  540. if (keyStart > 1 || valueStart > 1)
  541. {
  542. return;
  543. }
  544. //示例 ["aa",{"bbbb":123,"fff","ddd"}]
  545. switch (c)
  546. {
  547. case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]
  548. isError = jsonStart && state == 0;//重复开始错误 同时不是值处理。
  549. break;
  550. case '}':
  551. isError = !jsonStart || (keyStart != 0 && state == 0);//重复结束错误 或者 提前结束{"aa"}。正常的有{}
  552. break;
  553. case '[':
  554. isError = arrayStart && state == 0;//重复开始错误
  555. break;
  556. case ']':
  557. isError = !arrayStart || jsonStart;//重复开始错误 或者 Json 未结束
  558. break;
  559. case '"':
  560. case '\'':
  561. isError = !(jsonStart || arrayStart); //json 或数组开始。
  562. if (!isError)
  563. {
  564. //重复开始 [""",{"" "}]
  565. isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);
  566. }
  567. if (!isError && arrayStart && !jsonStart && c == '\'')//['aa',{}]
  568. {
  569. isError = true;
  570. }
  571. break;
  572. case ':':
  573. isError = !jsonStart || state == 1;//重复出现。
  574. break;
  575. case ',':
  576. isError = !(jsonStart || arrayStart); //json 或数组开始。
  577. if (!isError)
  578. {
  579. if (jsonStart)
  580. {
  581. isError = state == 0 || (state == 1 && valueStart > 1);//重复出现。
  582. }
  583. else if (arrayStart)//["aa,] [,] [{},{}]
  584. {
  585. isError = keyStart == 0 && !setDicValue;
  586. }
  587. }
  588. break;
  589. case ' ':
  590. case '\r':
  591. case '\n'://[ "a",\r\n{} ]
  592. case '\0':
  593. case '\t':
  594. break;
  595. default: //值开头。。
  596. isError = (!jsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);//
  597. break;
  598. }
  599. //if (isError)
  600. //{
  601. //}
  602. }
  603. }
  604. /// <summary>
  605. /// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理)
  606. /// </summary>
  607. private static bool SetCharState(char c, ref CharState cs)
  608. {
  609. cs.CheckIsError(c);
  610. switch (c)
  611. {
  612. case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]
  613. #region 大括号
  614. if (cs.keyStart <= 0 && cs.valueStart <= 0)
  615. {
  616. cs.keyStart = 0;
  617. cs.valueStart = 0;
  618. if (cs.jsonStart && cs.state == 1)
  619. {
  620. cs.childrenStart = true;
  621. }
  622. else
  623. {
  624. cs.state = 0;
  625. }
  626. cs.jsonStart = true;//开始。
  627. return true;
  628. }
  629. #endregion
  630. break;
  631. case '}':
  632. #region 大括号结束
  633. if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.jsonStart)
  634. {
  635. cs.jsonStart = false;//正常结束。
  636. cs.state = 0;
  637. cs.keyStart = 0;
  638. cs.valueStart = 0;
  639. cs.setDicValue = true;
  640. return true;
  641. }
  642. // cs.isError = !cs.jsonStart && cs.state == 0;
  643. #endregion
  644. break;
  645. case '[':
  646. #region 中括号开始
  647. if (!cs.jsonStart)
  648. {
  649. cs.arrayStart = true;
  650. return true;
  651. }
  652. else if (cs.jsonStart && cs.state == 1)
  653. {
  654. cs.childrenStart = true;
  655. return true;
  656. }
  657. #endregion
  658. break;
  659. case ']':
  660. #region 中括号结束
  661. if (cs.arrayStart && !cs.jsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//这样结束。
  662. {
  663. cs.keyStart = 0;
  664. cs.valueStart = 0;
  665. cs.arrayStart = false;
  666. return true;
  667. }
  668. #endregion
  669. break;
  670. case '"':
  671. case '\'':
  672. #region 引号
  673. if (cs.jsonStart || cs.arrayStart)
  674. {
  675. if (cs.state == 0)//key阶段,有可能是数组["aa",{}]
  676. {
  677. if (cs.keyStart <= 0)
  678. {
  679. cs.keyStart = (c == '"' ? 3 : 2);
  680. return true;
  681. }
  682. else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"'))
  683. {
  684. if (!cs.escapeChar)
  685. {
  686. cs.keyStart = -1;
  687. return true;
  688. }
  689. else
  690. {
  691. cs.escapeChar = false;
  692. }
  693. }
  694. }
  695. else if (cs.state == 1 && cs.jsonStart)//值阶段必须是Json开始了。
  696. {
  697. if (cs.valueStart <= 0)
  698. {
  699. cs.valueStart = (c == '"' ? 3 : 2);
  700. return true;
  701. }
  702. else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"'))
  703. {
  704. if (!cs.escapeChar)
  705. {
  706. cs.valueStart = -1;
  707. return true;
  708. }
  709. else
  710. {
  711. cs.escapeChar = false;
  712. }
  713. }
  714. }
  715. }
  716. #endregion
  717. break;
  718. case ':':
  719. #region 冒号
  720. if (cs.jsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0)
  721. {
  722. if (cs.keyStart == 1)
  723. {
  724. cs.keyStart = -1;
  725. }
  726. cs.state = 1;
  727. return true;
  728. }
  729. // cs.isError = !cs.jsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1);
  730. #endregion
  731. break;
  732. case ',':
  733. #region 逗号 //["aa",{aa:12,}]
  734. if (cs.jsonStart)
  735. {
  736. if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1)
  737. {
  738. cs.state = 0;
  739. cs.keyStart = 0;
  740. cs.valueStart = 0;
  741. //if (cs.valueStart == 1)
  742. //{
  743. // cs.valueStart = 0;
  744. //}
  745. cs.setDicValue = true;
  746. return true;
  747. }
  748. }
  749. else if (cs.arrayStart && cs.keyStart <= 2)
  750. {
  751. cs.keyStart = 0;
  752. //if (cs.keyStart == 1)
  753. //{
  754. // cs.keyStart = -1;
  755. //}
  756. return true;
  757. }
  758. #endregion
  759. break;
  760. case ' ':
  761. case '\r':
  762. case '\n'://[ "a",\r\n{} ]
  763. case '\0':
  764. case '\t':
  765. if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.jsonStart &&
  766. {
  767. return true;//跳过空格。
  768. }
  769. break;
  770. default: //值开头。。
  771. if (c == '\\') //转义符号
  772. {
  773. if (cs.escapeChar)
  774. {
  775. cs.escapeChar = false;
  776. }
  777. else
  778. {
  779. cs.escapeChar = true;
  780. return true;
  781. }
  782. }
  783. else
  784. {
  785. cs.escapeChar = false;
  786. }
  787. if (cs.jsonStart || cs.arrayStart) // Json 或数组开始了。
  788. {
  789. if (cs.keyStart <= 0 && cs.state == 0)
  790. {
  791. cs.keyStart = 1;//无引号的
  792. }
  793. else if (cs.valueStart <= 0 && cs.state == 1 && cs.jsonStart)//只有Json开始才有值。
  794. {
  795. cs.valueStart = 1;//无引号的
  796. }
  797. }
  798. break;
  799. }
  800. return false;
  801. }
  802. }
  803. }

WebApi的调用-2.后台调用的更多相关文章

  1. c#后台调用API

    前两周赶上项目第一个版本上线,着实忙了一把,毕竟只有两个人负责.如今已完结,总算喘了一口气,现在任务就是写API.测API,许久之前写过JS前台调用 项目API,也写过后台调用开放的手机号归属地查询, ...

  2. 使用OAuth、Identity创建WebApi认证接口供客户端调用

    前言 现在的web app基本上都是前后端分离,之前接触的大部分应用场景最终产品都是部署在同一个站点下,那么随着WebApi(Restful api)的发展前后端实现的完全分离,前端不在后端框架的页面 ...

  3. 获取ip ,百度地图坐标点 和 在 后台调用 url()

        protected  void getip()         {             string ips = HttpContext.Current.Request.UserHostA ...

  4. 由ASP.NET所谓前台调用后台、后台调用前台想到HTTP——实践篇(二)

    在由ASP.NET所谓前台调用后台.后台调用前台想到HTTP——理论篇中描述了一下ASP.NET新手的三个问题及相关的HTTP协议内容,在由ASP.NET所谓前台调用后台.后台调用前台想到HTTP—— ...

  5. 由ASP.NET所谓前台调用后台、后台调用前台想到HTTP——理论篇

    工作两年多了,我会经常尝试给公司小伙伴儿们解决一些问题,几个月下来我发现初入公司的小朋友最爱问的问题就三个 1. 我想前台调用后台的XXX方法怎么弄啊? 2. 我想后台调用前台的XXX JavaScr ...

  6. Javascript调用C#后台方法及JSon解析

    Javascript调用C#后台方法及JSon解析   如何使用Ajax 调用C# 后台方法. 本文目录 如何使用Ajax 调用C# 后台方法. 1.后台(.cs)测试方法 2.前台调用(javasc ...

  7. WebService – 3.后台调用WebService,根级别上的数据无效

    1.因为我的webservice返回的是json, 2.ajax传递跨域不安全, 3.contentType: "application/json; charset=utf-8", ...

  8. Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口

    1.WebApi系列~通过HttpClient来调用Web Api接口 http://www.cnblogs.com/lori/p/4045413.html HttpClient使用详解(java版本 ...

  9. js前台与后台数据交互-后台调前台(后台调用、注册客户端脚本)

    转自:http://blog.csdn.net/wang379275614/article/details/17049721 客户端脚本一般都在前台,这里讲的是(1)在后台调用前台定义的脚本(2)在后 ...

随机推荐

  1. SQL记录-Oracle重命名表名例子

    rename table_1 to table_2

  2. MVC模块化开发方案

    核心: 主要利用MVC的区域功能,实现项目模块独立开发和调试. 目标: 各个模块以独立MVC应用程序存在,即模块可独立开发和调试. 动态注册各个模块路由. 一:新建解决方案目录结构 如图: 二:Eas ...

  3. C# 实现线段的编码裁剪算法(vs2010)

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  4. FASTREPORT COM/ActiveX报表如何保存到C++项目中?

    可以的. VC++ : ... IStream * pStream;CreateStreamOnHGlobal(NULL, true, &pStream);pStream->AddRef ...

  5. js 碰撞 + 重力 运动

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. JavaScript之Ajax(一)创建Ajax对象

    // 支持浏览器的源码 function AjaxObject() { var AjaxRequest; // 缓存XHR对象便于 Ajax 使用 try { // Opera 8.0+, Firef ...

  7. JavaScript之字符串匹配工具[插件]

    /*** * StringCheckUtil * 字符串检测工具 * * @version 1.0 * @method isNum(string,scope) * @method isChinese( ...

  8. Mysql 插入中文错误:Incorrect string value: '\xE7\xA8\x8B\xE5\xBA\x8F...' for column 'course' at row 1

    create table my_user (    id tinyint(4) not null auto_increment,    account varchar(255) default nul ...

  9. 函数前加static与不加static的区别

    1:加了static后表示该函数失去了全局可见性,只在该函数所在的文件作用域内可见 2:当函数声明为static以后,编译器在该目标编译单元内只含有该函数的入口地址,没有函数名,其它编译单元便不能通过 ...

  10. python3之协程

    1.协程的概念 协程,又称微线程,纤程.英文名Coroutine. 线程是系统级别的它们由操作系统调度,而协程则是程序级别的由程序根据需要自己调度.在一个线程中会有很多函数,我们把这些函数称为子程序, ...