使用WebRequest 检测 手机号归属地。 C#通用 使用json 和可设定超时的WebClient
首先建立jsonObject,当然你也可以使用xml解析,目前介绍一下我使用的方法。
- /**********************************************************
- * 说明:Json通用转换类
- *********************************************************/
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Xfrog.Net
- {
- /// <summary>
- /// 用于构建属性值的回调
- /// </summary>
- /// <param name="Property"></param>
- public delegate void SetProperties(JsonObject Property);
- /// <summary>
- /// JsonObject属性值类型
- /// </summary>
- public enum JsonPropertyType
- {
- String,
- Object,
- Array,
- Number,
- Bool,
- Null
- }
- /// <summary>
- /// JSON通用对象
- /// </summary>
- public class JsonObject
- {
- private Dictionary<String, JsonProperty> _property;
- public JsonObject()
- {
- this._property = null;
- }
- public JsonObject(String jsonString)
- {
- this.Parse(ref jsonString);
- }
- public JsonObject(SetProperties callback)
- {
- if (callback != null)
- {
- callback(this);
- }
- }
- /// <summary>
- /// Json字符串解析
- /// </summary>
- /// <param name="jsonString"></param>
- private void Parse(ref String jsonString)
- {
- int len = jsonString.Length;
- if (String.IsNullOrEmpty(jsonString) || jsonString.Substring(0, 1) != "{" || jsonString.Substring(jsonString.Length - 1, 1) != "}")
- {
- throw new ArgumentException("传入文本不符合Json格式!" + jsonString);
- }
- Stack<Char> stack = new Stack<char>();
- Stack<Char> stackType = new Stack<char>();
- StringBuilder sb = new StringBuilder();
- Char cur;
- bool convert = false;
- bool isValue = false;
- JsonProperty last = null;
- for (int i = 1; i <= len - 2; i++)
- {
- cur = jsonString[i];
- if (cur == '}')
- {
- ;
- }
- if (cur == ' ' && stack.Count == 0)
- {
- ;
- }
- else if ((cur == '\'' || cur == '\"') && !convert && stack.Count == 0 && !isValue)
- {
- sb.Length = 0;
- stack.Push(cur);
- }
- else if ((cur == '\'' || cur == '\"') && !convert && stack.Count > 0 && stack.Peek() == cur && !isValue)
- {
- stack.Pop();
- }
- else if ((cur == '[' || cur == '{') && stack.Count == 0)
- {
- stackType.Push(cur == '[' ? ']' : '}');
- sb.Append(cur);
- }
- else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Peek() == cur)
- {
- stackType.Pop();
- sb.Append(cur);
- }
- else if (cur == ':' && stack.Count == 0 && stackType.Count == 0 && !isValue)
- {
- last = new JsonProperty();
- this[sb.ToString()] = last;
- isValue = true;
- sb.Length = 0;
- }
- else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
- {
- if (last != null)
- {
- String temp = sb.ToString();
- last.Parse(ref temp);
- }
- isValue = false;
- sb.Length = 0;
- }
- else
- {
- sb.Append(cur);
- }
- }
- if (sb.Length > 0 && last != null && last.Type == JsonPropertyType.Null)
- {
- String temp = sb.ToString();
- last.Parse(ref temp);
- }
- }
- /// <summary>
- /// 获取属性
- /// </summary>
- /// <param name="PropertyName"></param>
- /// <returns></returns>
- public JsonProperty this[String PropertyName]
- {
- get
- {
- JsonProperty result = null;
- if (this._property != null && this._property.ContainsKey(PropertyName))
- {
- result = this._property[PropertyName];
- }
- return result;
- }
- set
- {
- if (this._property == null)
- {
- this._property = new Dictionary<string, JsonProperty>(StringComparer.OrdinalIgnoreCase);
- }
- if (this._property.ContainsKey(PropertyName))
- {
- this._property[PropertyName] = value;
- }
- else
- {
- this._property.Add(PropertyName, value);
- }
- }
- }
- /// <summary>
- /// 通过此泛型函数可直接获取指定类型属性的值
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="PropertyName"></param>
- /// <returns></returns>
- public virtual T Properties<T>(String PropertyName) where T : class
- {
- JsonProperty p = this[PropertyName];
- if (p != null)
- {
- return p.GetValue<T>();
- }
- return default(T);
- }
- /// <summary>
- /// 获取属性名称列表
- /// </summary>
- /// <returns></returns>
- public String[] GetPropertyNames()
- {
- if (this._property == null)
- return null;
- String[] keys = null;
- if (this._property.Count > 0)
- {
- keys = new String[this._property.Count];
- this._property.Keys.CopyTo(keys, 0);
- }
- return keys;
- }
- /// <summary>
- /// 移除一个属性
- /// </summary>
- /// <param name="PropertyName"></param>
- /// <returns></returns>
- public JsonProperty RemoveProperty(String PropertyName)
- {
- if (this._property != null && this._property.ContainsKey(PropertyName))
- {
- JsonProperty p = this._property[PropertyName];
- this._property.Remove(PropertyName);
- return p;
- }
- return null;
- }
- /// <summary>
- /// 是否为空对象
- /// </summary>
- /// <returns></returns>
- public bool IsNull()
- {
- return this._property == null;
- }
- public override string ToString()
- {
- return this.ToString("");
- }
- /// <summary>
- /// ToString...
- /// </summary>
- /// <param name="format">格式化字符串</param>
- /// <returns></returns>
- public virtual string ToString(String format)
- {
- if (this.IsNull())
- {
- return "{}";
- }
- else
- {
- StringBuilder sb = new StringBuilder();
- foreach (String key in this._property.Keys)
- {
- sb.Append(",");
- sb.Append(key).Append(": ");
- sb.Append(this._property[key].ToString(format));
- }
- if (this._property.Count > 0)
- {
- sb.Remove(0, 1);
- }
- sb.Insert(0, "{");
- sb.Append("}");
- return sb.ToString();
- }
- }
- }
- /// <summary>
- /// JSON对象属性
- /// </summary>
- public class JsonProperty
- {
- private JsonPropertyType _type;
- private String _value;
- private JsonObject _object;
- private List<JsonProperty> _list;
- private bool _bool;
- private double _number;
- public JsonProperty()
- {
- this._type = JsonPropertyType.Null;
- this._value = null;
- this._object = null;
- this._list = null;
- }
- public JsonProperty(Object value)
- {
- this.SetValue(value);
- }
- public JsonProperty(String jsonString)
- {
- this.Parse(ref jsonString);
- }
- /// <summary>
- /// Json字符串解析
- /// </summary>
- /// <param name="jsonString"></param>
- public void Parse(ref String jsonString)
- {
- if (String.IsNullOrEmpty(jsonString))
- {
- this.SetValue(null);
- }
- else
- {
- string first = jsonString.Substring(0, 1);
- string last = jsonString.Substring(jsonString.Length - 1, 1);
- if (first == "[" && last == "]")
- {
- this.SetValue(this.ParseArray(ref jsonString));
- }
- else if (first == "{" && last == "}")
- {
- this.SetValue(this.ParseObject(ref jsonString));
- }
- else if ((first == "'" || first == "\"") && first == last)
- {
- this.SetValue(this.ParseString(ref jsonString));
- }
- else if (jsonString == "true" || jsonString == "false")
- {
- this.SetValue(jsonString == "true" ? true : false);
- }
- else if (jsonString == "null")
- {
- this.SetValue(null);
- }
- else
- {
- double d = 0;
- if (double.TryParse(jsonString, out d))
- {
- this.SetValue(d);
- }
- else
- {
- this.SetValue(jsonString);
- }
- }
- }
- }
- /// <summary>
- /// Json Array解析
- /// </summary>
- /// <param name="jsonString"></param>
- /// <returns></returns>
- private List<JsonProperty> ParseArray(ref String jsonString)
- {
- List<JsonProperty> list = new List<JsonProperty>();
- int len = jsonString.Length;
- StringBuilder sb = new StringBuilder();
- Stack<Char> stack = new Stack<char>();
- Stack<Char> stackType = new Stack<Char>();
- bool conver = false;
- Char cur;
- for (int i = 1; i <= len - 2; i++)
- {
- cur = jsonString[i];
- if (Char.IsWhiteSpace(cur) && stack.Count == 0)
- {
- ;
- }
- else if ((cur == '\'' && stack.Count == 0 && !conver && stackType.Count == 0) || (cur == '\"' && stack.Count == 0 && !conver && stackType.Count == 0))
- {
- sb.Length = 0;
- sb.Append(cur);
- stack.Push(cur);
- }
- else if (cur == '\\' && stack.Count > 0 && !conver)
- {
- sb.Append(cur);
- conver = true;
- }
- else if (conver == true)
- {
- conver = false;
- if (cur == 'u')
- {
- sb.Append(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3] });
- i += 4;
- }
- else
- {
- sb.Append(cur);
- }
- }
- else if ((cur == '\'' || cur == '\"') && !conver && stack.Count > 0 && stack.Peek() == cur && stackType.Count == 0)
- {
- sb.Append(cur);
- list.Add(new JsonProperty(sb.ToString()));
- stack.Pop();
- }
- else if ((cur == '[' || cur == '{') && stack.Count == 0)
- {
- if (stackType.Count == 0)
- {
- sb.Length = 0;
- }
- sb.Append(cur);
- stackType.Push((cur == '[' ? ']' : '}'));
- }
- else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Count > 0 && stackType.Peek() == cur)
- {
- sb.Append(cur);
- stackType.Pop();
- if (stackType.Count == 0)
- {
- list.Add(new JsonProperty(sb.ToString()));
- sb.Length = 0;
- }
- }
- else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
- {
- if (sb.Length > 0)
- {
- list.Add(new JsonProperty(sb.ToString()));
- sb.Length = 0;
- }
- }
- else
- {
- sb.Append(cur);
- }
- }
- if (stack.Count > 0 || stackType.Count > 0)
- {
- list.Clear();
- throw new ArgumentException("无法解析Json Array对象!");
- }
- else if (sb.Length > 0)
- {
- list.Add(new JsonProperty(sb.ToString()));
- }
- return list;
- }
- /// <summary>
- /// Json String解析
- /// </summary>
- /// <param name="jsonString"></param>
- /// <returns></returns>
- private String ParseString(ref String jsonString)
- {
- int len = jsonString.Length;
- StringBuilder sb = new StringBuilder();
- bool conver = false;
- Char cur;
- for (int i = 1; i <= len - 2; i++)
- {
- cur = jsonString[i];
- if (cur == '\\' && !conver)
- {
- conver = true;
- }
- else if (conver == true)
- {
- conver = false;
- if (cur == '\\' || cur == '\"' || cur == '\'' || cur == '/')
- {
- sb.Append(cur);
- }
- else
- {
- if (cur == 'u')
- {
- String temp = new String(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3] });
- sb.Append((char)Convert.ToInt32(temp, 16));
- i += 4;
- }
- else
- {
- switch (cur)
- {
- case 'b':
- sb.Append('\b');
- break;
- case 'f':
- sb.Append('\f');
- break;
- case 'n':
- sb.Append('\n');
- break;
- case 'r':
- sb.Append('\r');
- break;
- case 't':
- sb.Append('\t');
- break;
- }
- }
- }
- }
- else
- {
- sb.Append(cur);
- }
- }
- return sb.ToString();
- }
- /// <summary>
- /// Json Object解析
- /// </summary>
- /// <param name="jsonString"></param>
- /// <returns></returns>
- private JsonObject ParseObject(ref String jsonString)
- {
- return new JsonObject(jsonString);
- }
- /// <summary>
- /// 定义一个索引器,如果属性是非数组的,返回本身
- /// </summary>
- /// <param name="index"></param>
- /// <returns></returns>
- public JsonProperty this[int index]
- {
- get
- {
- JsonProperty r = null;
- if (this._type == JsonPropertyType.Array)
- {
- if (this._list != null && (this._list.Count - 1) >= index)
- {
- r = this._list[index];
- }
- }
- else if (index == 0)
- {
- return this;
- }
- return r;
- }
- }
- /// <summary>
- /// 提供一个字符串索引,简化对Object属性的访问
- /// </summary>
- /// <param name="PropertyName"></param>
- /// <returns></returns>
- public JsonProperty this[String PropertyName]
- {
- get
- {
- if (this._type == JsonPropertyType.Object)
- {
- return this._object[PropertyName];
- }
- else
- {
- return null;
- }
- }
- set
- {
- if (this._type == JsonPropertyType.Object)
- {
- this._object[PropertyName] = value;
- }
- else
- {
- throw new NotSupportedException("Json属性不是对象类型!");
- }
- }
- }
- /// <summary>
- /// JsonObject值
- /// </summary>
- public JsonObject Object
- {
- get
- {
- if (this._type == JsonPropertyType.Object)
- return this._object;
- return null;
- }
- }
- /// <summary>
- /// 字符串值
- /// </summary>
- public String Value
- {
- get
- {
- if (this._type == JsonPropertyType.String)
- {
- return this._value;
- }
- else if (this._type == JsonPropertyType.Number)
- {
- return this._number.ToString();
- }
- return null;
- }
- }
- public JsonProperty Add(Object value)
- {
- if (this._type != JsonPropertyType.Null && this._type != JsonPropertyType.Array)
- {
- throw new NotSupportedException("Json属性不是Array类型,无法添加元素!");
- }
- if (this._list == null)
- {
- this._list = new List<JsonProperty>();
- }
- JsonProperty jp = new JsonProperty(value);
- this._list.Add(jp);
- this._type = JsonPropertyType.Array;
- return jp;
- }
- /// <summary>
- /// Array值,如果属性是非数组的,则封装成只有一个元素的数组
- /// </summary>
- public List<JsonProperty> Items
- {
- get
- {
- if (this._type == JsonPropertyType.Array)
- {
- return this._list;
- }
- else
- {
- List<JsonProperty> list = new List<JsonProperty>();
- list.Add(this);
- return list;
- }
- }
- }
- /// <summary>
- /// 数值
- /// </summary>
- public double Number
- {
- get
- {
- if (this._type == JsonPropertyType.Number)
- {
- return this._number;
- }
- else
- {
- return double.NaN;
- }
- }
- }
- public void Clear()
- {
- this._type = JsonPropertyType.Null;
- this._value = String.Empty;
- this._object = null;
- if (this._list != null)
- {
- this._list.Clear();
- this._list = null;
- }
- }
- public Object GetValue()
- {
- if (this._type == JsonPropertyType.String)
- {
- return this._value;
- }
- else if (this._type == JsonPropertyType.Object)
- {
- return this._object;
- }
- else if (this._type == JsonPropertyType.Array)
- {
- return this._list;
- }
- else if (this._type == JsonPropertyType.Bool)
- {
- return this._bool;
- }
- else if (this._type == JsonPropertyType.Number)
- {
- return this._number;
- }
- else
- {
- return null;
- }
- }
- public virtual T GetValue<T>() where T : class
- {
- return (GetValue() as T);
- }
- public virtual void SetValue(Object value)
- {
- if (value is String)
- {
- this._type = JsonPropertyType.String;
- this._value = (String)value;
- }
- else if (value is List<JsonProperty>)
- {
- this._list = ((List<JsonProperty>)value);
- this._type = JsonPropertyType.Array;
- }
- else if (value is JsonObject)
- {
- this._object = (JsonObject)value;
- this._type = JsonPropertyType.Object;
- }
- else if (value is bool)
- {
- this._bool = (bool)value;
- this._type = JsonPropertyType.Bool;
- }
- else if (value == null)
- {
- this._type = JsonPropertyType.Null;
- }
- else
- {
- double d = 0;
- if (double.TryParse(value.ToString(), out d))
- {
- this._number = d;
- this._type = JsonPropertyType.Number;
- }
- else
- {
- throw new ArgumentException("错误的参数类型!");
- }
- }
- }
- public virtual int Count
- {
- get
- {
- int c = 0;
- if (this._type == JsonPropertyType.Array)
- {
- if (this._list != null)
- {
- c = this._list.Count;
- }
- }
- else
- {
- c = 1;
- }
- return c;
- }
- }
- public JsonPropertyType Type
- {
- get { return this._type; }
- }
- public override string ToString()
- {
- return this.ToString("");
- }
- public virtual string ToString(String format)
- {
- StringBuilder sb = new StringBuilder();
- if (this._type == JsonPropertyType.String)
- {
- sb.Append("'").Append(this._value).Append("'");
- return sb.ToString();
- }
- else if (this._type == JsonPropertyType.Bool)
- {
- return this._bool ? "true" : "false";
- }
- else if (this._type == JsonPropertyType.Number)
- {
- return this._number.ToString();
- }
- else if (this._type == JsonPropertyType.Null)
- {
- return "null";
- }
- else if (this._type == JsonPropertyType.Object)
- {
- return this._object.ToString();
- }
- else
- {
- if (this._list == null || this._list.Count == 0)
- {
- sb.Append("[]");
- }
- else
- {
- sb.Append("[");
- if (this._list.Count > 0)
- {
- foreach (JsonProperty p in this._list)
- {
- sb.Append(p.ToString());
- sb.Append(", ");
- }
- sb.Length -= 2;
- }
- sb.Append("]");
- }
- return sb.ToString();
- }
- }
- }
- }
然后是调用地址 和方法
- public int validateNumber(string mobileNo)
- {
- string url = ServiceConfig.serviceUrl["validateNumber"].ToString();
- string paramsString = "m=" + mobileNo + "&output=json";
- string result = CommonTools.httpPostByUrl(url, paramsString);
- if (!result.Equals(""))
- {
- JsonObject resultJson = new JsonObject(result);
- if (resultJson.Properties<string>("QueryResult").Equals("True") && resultJson.Properties<string>("Province").Equals("江西"))
- {
- //成功返回0
- return 0;
- }
- else if (result.Equals(""))
- {
- return 1;
- }
- //失败返回1
- }
- return 1;
- }
- /// <summary>
- /// 调用httpPost接口
- /// </summary>
- /// <param name="url"></param>
- /// <param name="paramsString"></param>
- /// <returns></returns>
- public static string httpPostByUrl(string url, string paramsString)
- {
- try
- {
- using (var client = new ExtendedWebClient())
- {
- client.Timeout = 3000;
- client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
- byte[] postData = Encoding.ASCII.GetBytes(paramsString);
- byte[] responseData = client.UploadData(url, "POST", postData);
- string result = Encoding.UTF8.GetString(responseData);
- Console.WriteLine("httpPost result:" + result);
- return result;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex);
- return "";
- }
- }
扩展的webCilent
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- namespace QinQinGo.Common
- {
- public class ExtendedWebClient : WebClient
- {
- public int Timeout { get; set; }
- protected override WebRequest GetWebRequest(Uri address)
- {
- WebRequest request = base.GetWebRequest(address);
- if (request != null)
- request.Timeout = Timeout;
- return request;
- }
- public ExtendedWebClient()
- {
- Timeout = 100000; // the standard HTTP Request Timeout default
- }
- }
- }
最后是接口地址:
http://api.showji.com/Locating/default.aspx
使用WebRequest 检测 手机号归属地。 C#通用 使用json 和可设定超时的WebClient的更多相关文章
- 一个相对通用的JSON响应结构,其中包含两部分:元数据与返回值
定义一个相对通用的JSON响应结构,其中包含两部分:元数据与返回值,其中,元数据表示操作是否成功与返回值消息等,返回值对应服务端方法所返回的数据. public class Response { pr ...
- java获取手机号归属地
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
- js 检测 flash插件以及版本号 通用所有浏览器
var fls = flashChecker(); if (fls.h) { if (fls.v < parseFloat('8.0')) { alert("您当前的flash pla ...
- java URL 利用网址api 查出手机号归属地
手机号码归属地查询api接口 1.淘宝网API地址: http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手机号码参数:tel:手机号码返 ...
- C# 编写通用的JSON数据进行序列化和反序列化
注意事项:使用JSON系列化和反系列化,必须要添加引用System.Runtime.Serialization. 1.通用类代码如下: /// <summary> /// JSON序 ...
- C# Dynamic通用反序列化Json类型并遍历属性比较
背景 : 最近在做JAVA 3D API重写,重写的结果需要与原有的API结果进行比较,只有结果一致时才能说明接口是等价重写的,为此需要做一个API结果比较的工具,比较的内容就是Json内容,但是为了 ...
- APISpace 空号检测API接口 免费好用
空号检测也称空号在线过滤,在线筛号,号码在线清洗.空号检测平台借助第五代大数据空号检测系统,为用户提供高精准的空号检测.号码过滤.号码筛选.号码清洗等众多号码检测功能,让用户快速准确的检测出活跃号.空 ...
- Spring入门(7)-自动检测Bean
Spring入门(7)-自动检测Bean 本文介绍如何自动检测Bean. 0. 目录 使用component-scan自动扫描 为自动检测标注Bean 1. 使用component-scan自动扫描 ...
- 15_CXF和Spring开发手机号查询网站
[整体分析] [生成客户端代码] wsdl网址: http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx 生成的客户端代码 [工程截图(已拷入客户端 ...
随机推荐
- 原生Android动作
ACTION_ALL_APPS:打开一个列出所有已安装应用程序的Activity.通常,此操作又启动器处理. ACTION_ANSWER:打开一个处理来电的Activity,通常这个动作是由本地电话拨 ...
- JSP基本面试的试题
JSP基本面试的试题 1.jsp有哪些内置对象作用分别是什么 答:JSP共有以下9种基本内置组件(可与ASP的6种内部组件相对应): request 用户端请求,此请求会包含来自GET/PO ...
- 响应式Web设计(Responsive Web design)
中文名 响应式Web设计 提出时间 2010年5月 英 文 Responsive Web design 解 释 一个网站能够兼容多个终端 目 的 解决移动互联网的浏览 优 点 ...
- 【OpenStack】OpenStack系列5之Cinder详解
源码下载安装 git clone -b stable/icehouse https://github.com/openstack/cinder.git pip install -r requireme ...
- 【Spring】Spring系列7之Spring整合MVC框架
7.Spring整合MVC框架 7.1.web环境中使用Spring 7.2.整合MVC框架 目标:使用Spring管理MVC的Action.Controller 最佳实践参考:http://www. ...
- 转数据库分库分表(sharding)系列(一) 拆分实施策略和示例演示
本文原文连接: http://blog.csdn.net/bluishglc/article/details/7696085 ,转载请注明出处!本文着重介绍sharding切分策略,如果你对数据库sh ...
- 好玩儿的expect
前言 1> 借鉴里面的应用思想,使用断言提高代码的健壮性及维护性 2> 实现方式——不采用直接嵌入expect的方式,统一进行重写(提取常用断言方法,重新构造API) 官网介绍 https ...
- Android中mesure过程详解
我们在编写layout的xml文件时会碰到layout_width和layout_height两个属性,对于这两个属性我们有三种选择:赋值成具体的数值,match_parent或者wrap_conte ...
- 一、HTML和CSS基础--开发工具--Sublime前端开发工具技巧介绍
下载:官网下载(根据系统下载) 安装:按步骤安装即可 注意:当前稳定版本为2,但3的功能有提升:Mac和Windows下的快捷键不同 优点:启动速度快,界面简洁,可以直接打开图片. 1 菜单栏主要功能 ...
- 记C语言浮点数运算处理 "坑" 一则
看一小段C语言程序: int main() { float x = 1.3; x = x - (int)x; ); ; } 在你心目中, 变量 I 是怎样的结果? 如果你理所当然地认为是3的话, 那么 ...