使用WebRequest 检测 手机号归属地。 C#通用 使用json 和可设定超时的WebClient

时间:2023-03-09 22:46:13
使用WebRequest 检测 手机号归属地。 C#通用 使用json 和可设定超时的WebClient

首先建立jsonObject,当然你也可以使用xml解析,目前介绍一下我使用的方法。

  1. /**********************************************************
  2. * 说明:Json通用转换类
  3. *********************************************************/
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. namespace Xfrog.Net
  8. {
  9. /// <summary>
  10. /// 用于构建属性值的回调
  11. /// </summary>
  12. /// <param name="Property"></param>
  13. public delegate void SetProperties(JsonObject Property);
  14. /// <summary>
  15. /// JsonObject属性值类型
  16. /// </summary>
  17. public enum JsonPropertyType
  18. {
  19. String,
  20. Object,
  21. Array,
  22. Number,
  23. Bool,
  24. Null
  25. }
  26. /// <summary>
  27. /// JSON通用对象
  28. /// </summary>
  29. public class JsonObject
  30. {
  31. private Dictionary<String, JsonProperty> _property;
  32. public JsonObject()
  33. {
  34. this._property = null;
  35. }
  36. public JsonObject(String jsonString)
  37. {
  38. this.Parse(ref jsonString);
  39. }
  40. public JsonObject(SetProperties callback)
  41. {
  42. if (callback != null)
  43. {
  44. callback(this);
  45. }
  46. }
  47. /// <summary>
  48. /// Json字符串解析
  49. /// </summary>
  50. /// <param name="jsonString"></param>
  51. private void Parse(ref String jsonString)
  52. {
  53. int len = jsonString.Length;
  54. if (String.IsNullOrEmpty(jsonString) || jsonString.Substring(0, 1) != "{" || jsonString.Substring(jsonString.Length - 1, 1) != "}")
  55. {
  56. throw new ArgumentException("传入文本不符合Json格式!" + jsonString);
  57. }
  58. Stack<Char> stack = new Stack<char>();
  59. Stack<Char> stackType = new Stack<char>();
  60. StringBuilder sb = new StringBuilder();
  61. Char cur;
  62. bool convert = false;
  63. bool isValue = false;
  64. JsonProperty last = null;
  65. for (int i = 1; i <= len - 2; i++)
  66. {
  67. cur = jsonString[i];
  68. if (cur == '}')
  69. {
  70. ;
  71. }
  72. if (cur == ' ' && stack.Count == 0)
  73. {
  74. ;
  75. }
  76. else if ((cur == '\'' || cur == '\"') && !convert && stack.Count == 0 && !isValue)
  77. {
  78. sb.Length = 0;
  79. stack.Push(cur);
  80. }
  81. else if ((cur == '\'' || cur == '\"') && !convert && stack.Count > 0 && stack.Peek() == cur && !isValue)
  82. {
  83. stack.Pop();
  84. }
  85. else if ((cur == '[' || cur == '{') && stack.Count == 0)
  86. {
  87. stackType.Push(cur == '[' ? ']' : '}');
  88. sb.Append(cur);
  89. }
  90. else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Peek() == cur)
  91. {
  92. stackType.Pop();
  93. sb.Append(cur);
  94. }
  95. else if (cur == ':' && stack.Count == 0 && stackType.Count == 0 && !isValue)
  96. {
  97. last = new JsonProperty();
  98. this[sb.ToString()] = last;
  99. isValue = true;
  100. sb.Length = 0;
  101. }
  102. else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
  103. {
  104. if (last != null)
  105. {
  106. String temp = sb.ToString();
  107. last.Parse(ref temp);
  108. }
  109. isValue = false;
  110. sb.Length = 0;
  111. }
  112. else
  113. {
  114. sb.Append(cur);
  115. }
  116. }
  117. if (sb.Length > 0 && last != null && last.Type == JsonPropertyType.Null)
  118. {
  119. String temp = sb.ToString();
  120. last.Parse(ref temp);
  121. }
  122. }
  123. /// <summary>
  124. /// 获取属性
  125. /// </summary>
  126. /// <param name="PropertyName"></param>
  127. /// <returns></returns>
  128. public JsonProperty this[String PropertyName]
  129. {
  130. get
  131. {
  132. JsonProperty result = null;
  133. if (this._property != null && this._property.ContainsKey(PropertyName))
  134. {
  135. result = this._property[PropertyName];
  136. }
  137. return result;
  138. }
  139. set
  140. {
  141. if (this._property == null)
  142. {
  143. this._property = new Dictionary<string, JsonProperty>(StringComparer.OrdinalIgnoreCase);
  144. }
  145. if (this._property.ContainsKey(PropertyName))
  146. {
  147. this._property[PropertyName] = value;
  148. }
  149. else
  150. {
  151. this._property.Add(PropertyName, value);
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// 通过此泛型函数可直接获取指定类型属性的值
  157. /// </summary>
  158. /// <typeparam name="T"></typeparam>
  159. /// <param name="PropertyName"></param>
  160. /// <returns></returns>
  161. public virtual T Properties<T>(String PropertyName) where T : class
  162. {
  163. JsonProperty p = this[PropertyName];
  164. if (p != null)
  165. {
  166. return p.GetValue<T>();
  167. }
  168. return default(T);
  169. }
  170. /// <summary>
  171. /// 获取属性名称列表
  172. /// </summary>
  173. /// <returns></returns>
  174. public String[] GetPropertyNames()
  175. {
  176. if (this._property == null)
  177. return null;
  178. String[] keys = null;
  179. if (this._property.Count > 0)
  180. {
  181. keys = new String[this._property.Count];
  182. this._property.Keys.CopyTo(keys, 0);
  183. }
  184. return keys;
  185. }
  186. /// <summary>
  187. /// 移除一个属性
  188. /// </summary>
  189. /// <param name="PropertyName"></param>
  190. /// <returns></returns>
  191. public JsonProperty RemoveProperty(String PropertyName)
  192. {
  193. if (this._property != null && this._property.ContainsKey(PropertyName))
  194. {
  195. JsonProperty p = this._property[PropertyName];
  196. this._property.Remove(PropertyName);
  197. return p;
  198. }
  199. return null;
  200. }
  201. /// <summary>
  202. /// 是否为空对象
  203. /// </summary>
  204. /// <returns></returns>
  205. public bool IsNull()
  206. {
  207. return this._property == null;
  208. }
  209. public override string ToString()
  210. {
  211. return this.ToString("");
  212. }
  213. /// <summary>
  214. /// ToString...
  215. /// </summary>
  216. /// <param name="format">格式化字符串</param>
  217. /// <returns></returns>
  218. public virtual string ToString(String format)
  219. {
  220. if (this.IsNull())
  221. {
  222. return "{}";
  223. }
  224. else
  225. {
  226. StringBuilder sb = new StringBuilder();
  227. foreach (String key in this._property.Keys)
  228. {
  229. sb.Append(",");
  230. sb.Append(key).Append(": ");
  231. sb.Append(this._property[key].ToString(format));
  232. }
  233. if (this._property.Count > 0)
  234. {
  235. sb.Remove(0, 1);
  236. }
  237. sb.Insert(0, "{");
  238. sb.Append("}");
  239. return sb.ToString();
  240. }
  241. }
  242. }
  243. /// <summary>
  244. /// JSON对象属性
  245. /// </summary>
  246. public class JsonProperty
  247. {
  248. private JsonPropertyType _type;
  249. private String _value;
  250. private JsonObject _object;
  251. private List<JsonProperty> _list;
  252. private bool _bool;
  253. private double _number;
  254. public JsonProperty()
  255. {
  256. this._type = JsonPropertyType.Null;
  257. this._value = null;
  258. this._object = null;
  259. this._list = null;
  260. }
  261. public JsonProperty(Object value)
  262. {
  263. this.SetValue(value);
  264. }
  265. public JsonProperty(String jsonString)
  266. {
  267. this.Parse(ref jsonString);
  268. }
  269. /// <summary>
  270. /// Json字符串解析
  271. /// </summary>
  272. /// <param name="jsonString"></param>
  273. public void Parse(ref String jsonString)
  274. {
  275. if (String.IsNullOrEmpty(jsonString))
  276. {
  277. this.SetValue(null);
  278. }
  279. else
  280. {
  281. string first = jsonString.Substring(0, 1);
  282. string last = jsonString.Substring(jsonString.Length - 1, 1);
  283. if (first == "[" && last == "]")
  284. {
  285. this.SetValue(this.ParseArray(ref jsonString));
  286. }
  287. else if (first == "{" && last == "}")
  288. {
  289. this.SetValue(this.ParseObject(ref jsonString));
  290. }
  291. else if ((first == "'" || first == "\"") && first == last)
  292. {
  293. this.SetValue(this.ParseString(ref jsonString));
  294. }
  295. else if (jsonString == "true" || jsonString == "false")
  296. {
  297. this.SetValue(jsonString == "true" ? true : false);
  298. }
  299. else if (jsonString == "null")
  300. {
  301. this.SetValue(null);
  302. }
  303. else
  304. {
  305. double d = 0;
  306. if (double.TryParse(jsonString, out d))
  307. {
  308. this.SetValue(d);
  309. }
  310. else
  311. {
  312. this.SetValue(jsonString);
  313. }
  314. }
  315. }
  316. }
  317. /// <summary>
  318. /// Json Array解析
  319. /// </summary>
  320. /// <param name="jsonString"></param>
  321. /// <returns></returns>
  322. private List<JsonProperty> ParseArray(ref String jsonString)
  323. {
  324. List<JsonProperty> list = new List<JsonProperty>();
  325. int len = jsonString.Length;
  326. StringBuilder sb = new StringBuilder();
  327. Stack<Char> stack = new Stack<char>();
  328. Stack<Char> stackType = new Stack<Char>();
  329. bool conver = false;
  330. Char cur;
  331. for (int i = 1; i <= len - 2; i++)
  332. {
  333. cur = jsonString[i];
  334. if (Char.IsWhiteSpace(cur) && stack.Count == 0)
  335. {
  336. ;
  337. }
  338. else if ((cur == '\'' && stack.Count == 0 && !conver && stackType.Count == 0) || (cur == '\"' && stack.Count == 0 && !conver && stackType.Count == 0))
  339. {
  340. sb.Length = 0;
  341. sb.Append(cur);
  342. stack.Push(cur);
  343. }
  344. else if (cur == '\\' && stack.Count > 0 && !conver)
  345. {
  346. sb.Append(cur);
  347. conver = true;
  348. }
  349. else if (conver == true)
  350. {
  351. conver = false;
  352. if (cur == 'u')
  353. {
  354. sb.Append(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3] });
  355. i += 4;
  356. }
  357. else
  358. {
  359. sb.Append(cur);
  360. }
  361. }
  362. else if ((cur == '\'' || cur == '\"') && !conver && stack.Count > 0 && stack.Peek() == cur && stackType.Count == 0)
  363. {
  364. sb.Append(cur);
  365. list.Add(new JsonProperty(sb.ToString()));
  366. stack.Pop();
  367. }
  368. else if ((cur == '[' || cur == '{') && stack.Count == 0)
  369. {
  370. if (stackType.Count == 0)
  371. {
  372. sb.Length = 0;
  373. }
  374. sb.Append(cur);
  375. stackType.Push((cur == '[' ? ']' : '}'));
  376. }
  377. else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Count > 0 && stackType.Peek() == cur)
  378. {
  379. sb.Append(cur);
  380. stackType.Pop();
  381. if (stackType.Count == 0)
  382. {
  383. list.Add(new JsonProperty(sb.ToString()));
  384. sb.Length = 0;
  385. }
  386. }
  387. else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
  388. {
  389. if (sb.Length > 0)
  390. {
  391. list.Add(new JsonProperty(sb.ToString()));
  392. sb.Length = 0;
  393. }
  394. }
  395. else
  396. {
  397. sb.Append(cur);
  398. }
  399. }
  400. if (stack.Count > 0 || stackType.Count > 0)
  401. {
  402. list.Clear();
  403. throw new ArgumentException("无法解析Json Array对象!");
  404. }
  405. else if (sb.Length > 0)
  406. {
  407. list.Add(new JsonProperty(sb.ToString()));
  408. }
  409. return list;
  410. }
  411. /// <summary>
  412. /// Json String解析
  413. /// </summary>
  414. /// <param name="jsonString"></param>
  415. /// <returns></returns>
  416. private String ParseString(ref String jsonString)
  417. {
  418. int len = jsonString.Length;
  419. StringBuilder sb = new StringBuilder();
  420. bool conver = false;
  421. Char cur;
  422. for (int i = 1; i <= len - 2; i++)
  423. {
  424. cur = jsonString[i];
  425. if (cur == '\\' && !conver)
  426. {
  427. conver = true;
  428. }
  429. else if (conver == true)
  430. {
  431. conver = false;
  432. if (cur == '\\' || cur == '\"' || cur == '\'' || cur == '/')
  433. {
  434. sb.Append(cur);
  435. }
  436. else
  437. {
  438. if (cur == 'u')
  439. {
  440. String temp = new String(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3] });
  441. sb.Append((char)Convert.ToInt32(temp, 16));
  442. i += 4;
  443. }
  444. else
  445. {
  446. switch (cur)
  447. {
  448. case 'b':
  449. sb.Append('\b');
  450. break;
  451. case 'f':
  452. sb.Append('\f');
  453. break;
  454. case 'n':
  455. sb.Append('\n');
  456. break;
  457. case 'r':
  458. sb.Append('\r');
  459. break;
  460. case 't':
  461. sb.Append('\t');
  462. break;
  463. }
  464. }
  465. }
  466. }
  467. else
  468. {
  469. sb.Append(cur);
  470. }
  471. }
  472. return sb.ToString();
  473. }
  474. /// <summary>
  475. /// Json Object解析
  476. /// </summary>
  477. /// <param name="jsonString"></param>
  478. /// <returns></returns>
  479. private JsonObject ParseObject(ref String jsonString)
  480. {
  481. return new JsonObject(jsonString);
  482. }
  483. /// <summary>
  484. /// 定义一个索引器,如果属性是非数组的,返回本身
  485. /// </summary>
  486. /// <param name="index"></param>
  487. /// <returns></returns>
  488. public JsonProperty this[int index]
  489. {
  490. get
  491. {
  492. JsonProperty r = null;
  493. if (this._type == JsonPropertyType.Array)
  494. {
  495. if (this._list != null && (this._list.Count - 1) >= index)
  496. {
  497. r = this._list[index];
  498. }
  499. }
  500. else if (index == 0)
  501. {
  502. return this;
  503. }
  504. return r;
  505. }
  506. }
  507. /// <summary>
  508. /// 提供一个字符串索引,简化对Object属性的访问
  509. /// </summary>
  510. /// <param name="PropertyName"></param>
  511. /// <returns></returns>
  512. public JsonProperty this[String PropertyName]
  513. {
  514. get
  515. {
  516. if (this._type == JsonPropertyType.Object)
  517. {
  518. return this._object[PropertyName];
  519. }
  520. else
  521. {
  522. return null;
  523. }
  524. }
  525. set
  526. {
  527. if (this._type == JsonPropertyType.Object)
  528. {
  529. this._object[PropertyName] = value;
  530. }
  531. else
  532. {
  533. throw new NotSupportedException("Json属性不是对象类型!");
  534. }
  535. }
  536. }
  537. /// <summary>
  538. /// JsonObject值
  539. /// </summary>
  540. public JsonObject Object
  541. {
  542. get
  543. {
  544. if (this._type == JsonPropertyType.Object)
  545. return this._object;
  546. return null;
  547. }
  548. }
  549. /// <summary>
  550. /// 字符串值
  551. /// </summary>
  552. public String Value
  553. {
  554. get
  555. {
  556. if (this._type == JsonPropertyType.String)
  557. {
  558. return this._value;
  559. }
  560. else if (this._type == JsonPropertyType.Number)
  561. {
  562. return this._number.ToString();
  563. }
  564. return null;
  565. }
  566. }
  567. public JsonProperty Add(Object value)
  568. {
  569. if (this._type != JsonPropertyType.Null && this._type != JsonPropertyType.Array)
  570. {
  571. throw new NotSupportedException("Json属性不是Array类型,无法添加元素!");
  572. }
  573. if (this._list == null)
  574. {
  575. this._list = new List<JsonProperty>();
  576. }
  577. JsonProperty jp = new JsonProperty(value);
  578. this._list.Add(jp);
  579. this._type = JsonPropertyType.Array;
  580. return jp;
  581. }
  582. /// <summary>
  583. /// Array值,如果属性是非数组的,则封装成只有一个元素的数组
  584. /// </summary>
  585. public List<JsonProperty> Items
  586. {
  587. get
  588. {
  589. if (this._type == JsonPropertyType.Array)
  590. {
  591. return this._list;
  592. }
  593. else
  594. {
  595. List<JsonProperty> list = new List<JsonProperty>();
  596. list.Add(this);
  597. return list;
  598. }
  599. }
  600. }
  601. /// <summary>
  602. /// 数值
  603. /// </summary>
  604. public double Number
  605. {
  606. get
  607. {
  608. if (this._type == JsonPropertyType.Number)
  609. {
  610. return this._number;
  611. }
  612. else
  613. {
  614. return double.NaN;
  615. }
  616. }
  617. }
  618. public void Clear()
  619. {
  620. this._type = JsonPropertyType.Null;
  621. this._value = String.Empty;
  622. this._object = null;
  623. if (this._list != null)
  624. {
  625. this._list.Clear();
  626. this._list = null;
  627. }
  628. }
  629. public Object GetValue()
  630. {
  631. if (this._type == JsonPropertyType.String)
  632. {
  633. return this._value;
  634. }
  635. else if (this._type == JsonPropertyType.Object)
  636. {
  637. return this._object;
  638. }
  639. else if (this._type == JsonPropertyType.Array)
  640. {
  641. return this._list;
  642. }
  643. else if (this._type == JsonPropertyType.Bool)
  644. {
  645. return this._bool;
  646. }
  647. else if (this._type == JsonPropertyType.Number)
  648. {
  649. return this._number;
  650. }
  651. else
  652. {
  653. return null;
  654. }
  655. }
  656. public virtual T GetValue<T>() where T : class
  657. {
  658. return (GetValue() as T);
  659. }
  660. public virtual void SetValue(Object value)
  661. {
  662. if (value is String)
  663. {
  664. this._type = JsonPropertyType.String;
  665. this._value = (String)value;
  666. }
  667. else if (value is List<JsonProperty>)
  668. {
  669. this._list = ((List<JsonProperty>)value);
  670. this._type = JsonPropertyType.Array;
  671. }
  672. else if (value is JsonObject)
  673. {
  674. this._object = (JsonObject)value;
  675. this._type = JsonPropertyType.Object;
  676. }
  677. else if (value is bool)
  678. {
  679. this._bool = (bool)value;
  680. this._type = JsonPropertyType.Bool;
  681. }
  682. else if (value == null)
  683. {
  684. this._type = JsonPropertyType.Null;
  685. }
  686. else
  687. {
  688. double d = 0;
  689. if (double.TryParse(value.ToString(), out d))
  690. {
  691. this._number = d;
  692. this._type = JsonPropertyType.Number;
  693. }
  694. else
  695. {
  696. throw new ArgumentException("错误的参数类型!");
  697. }
  698. }
  699. }
  700. public virtual int Count
  701. {
  702. get
  703. {
  704. int c = 0;
  705. if (this._type == JsonPropertyType.Array)
  706. {
  707. if (this._list != null)
  708. {
  709. c = this._list.Count;
  710. }
  711. }
  712. else
  713. {
  714. c = 1;
  715. }
  716. return c;
  717. }
  718. }
  719. public JsonPropertyType Type
  720. {
  721. get { return this._type; }
  722. }
  723. public override string ToString()
  724. {
  725. return this.ToString("");
  726. }
  727. public virtual string ToString(String format)
  728. {
  729. StringBuilder sb = new StringBuilder();
  730. if (this._type == JsonPropertyType.String)
  731. {
  732. sb.Append("'").Append(this._value).Append("'");
  733. return sb.ToString();
  734. }
  735. else if (this._type == JsonPropertyType.Bool)
  736. {
  737. return this._bool ? "true" : "false";
  738. }
  739. else if (this._type == JsonPropertyType.Number)
  740. {
  741. return this._number.ToString();
  742. }
  743. else if (this._type == JsonPropertyType.Null)
  744. {
  745. return "null";
  746. }
  747. else if (this._type == JsonPropertyType.Object)
  748. {
  749. return this._object.ToString();
  750. }
  751. else
  752. {
  753. if (this._list == null || this._list.Count == 0)
  754. {
  755. sb.Append("[]");
  756. }
  757. else
  758. {
  759. sb.Append("[");
  760. if (this._list.Count > 0)
  761. {
  762. foreach (JsonProperty p in this._list)
  763. {
  764. sb.Append(p.ToString());
  765. sb.Append(", ");
  766. }
  767. sb.Length -= 2;
  768. }
  769. sb.Append("]");
  770. }
  771. return sb.ToString();
  772. }
  773. }
  774. }
  775. }

然后是调用地址 和方法

  1. public int validateNumber(string mobileNo)
  2. {
  3. string url = ServiceConfig.serviceUrl["validateNumber"].ToString();
  4. string paramsString = "m=" + mobileNo + "&output=json";
  5. string result = CommonTools.httpPostByUrl(url, paramsString);
  6. if (!result.Equals(""))
  7. {
  8. JsonObject resultJson = new JsonObject(result);
  9. if (resultJson.Properties<string>("QueryResult").Equals("True") && resultJson.Properties<string>("Province").Equals("江西"))
  10. {
  11. //成功返回0
  12. return 0;
  13. }
  14. else if (result.Equals(""))
  15. {
  16. return 1;
  17. }
  18. //失败返回1
  19. }
  20. return 1;
  21. }
  1. /// <summary>
  2. /// 调用httpPost接口
  3. /// </summary>
  4. /// <param name="url"></param>
  5. /// <param name="paramsString"></param>
  6. /// <returns></returns>
  7. public static string httpPostByUrl(string url, string paramsString)
  8. {
  9. try
  10. {
  11. using (var client = new ExtendedWebClient())
  12. {
  13. client.Timeout = 3000;
  14. client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  15. byte[] postData = Encoding.ASCII.GetBytes(paramsString);
  16. byte[] responseData = client.UploadData(url, "POST", postData);
  17. string result = Encoding.UTF8.GetString(responseData);
  18. Console.WriteLine("httpPost result:" + result);
  19. return result;
  20. }
  21. }
  22. catch (Exception ex)
  23. {
  24. Console.WriteLine(ex);
  25. return "";
  26. }
  27. }

扩展的webCilent

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. namespace QinQinGo.Common
  7. {
  8. public class ExtendedWebClient : WebClient
  9. {
  10. public int Timeout { get; set; }
  11. protected override WebRequest GetWebRequest(Uri address)
  12. {
  13. WebRequest request = base.GetWebRequest(address);
  14. if (request != null)
  15. request.Timeout = Timeout;
  16. return request;
  17. }
  18. public ExtendedWebClient()
  19. {
  20. Timeout = 100000; // the standard HTTP Request Timeout default
  21. }
  22. }
  23. }

最后是接口地址:

http://api.showji.com/Locating/default.aspx