日期:2014-05-18 浏览次数:20874 次
private string m_Location = "", m_IpAddress = "", m_Response = ""; /// <summary> /// 新建IpLocation实例以获得IP地理位置 /// </summary> /// <param name="ipAddress"></param> public IpLocation(string ipAddress) { m_IpAddress = ipAddress.Trim(); string[] ip = ipAddress.Split('.'); ipAddress = ip[0] + "." + ip[1] + ".1.1"; WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.GetEncoding("GB2312"); string url = "http://www.ip138.com/ips.asp"; string post = "ip=" + ipAddress + "&action=2"; client.Headers.Set("Content-Type", "application/x-www-form-urlencoded"); //尤其是这一句 string response = client.UploadString(url, post); //这里 m_Response = response; string p = @"<li>参考数据二:(?<location>[^<>]+?)</li>"; //和这一句 Match match = Regex.Match(response, p); //还有这里 m_Location = match.Groups["location"].Value.Trim(); //和这里 } /// <summary> /// 返回Ip地址的地理位置名称 /// </summary> public string Location { get { return m_Location; } } public string IpAddress { get { return m_IpAddress; } } /// <summary> /// 返回网络反馈原始数据 /// </summary> public string Response { get { return m_Response; } }
// 指定表单向服务器提交的编码类型,默认就上这个 client.Headers.Set("Content-Type", "application/x-www-form-urlencoded"); //尤其是这一句 // 向"http://www.ip138.com/ips.asp";页面post数据 string response = client.UploadString(url, post); //这里 m_Response = response; // 用于解析结果的正则表达式 string p = @"<li>参考数据二:(?<location>[^<>]+?)</li>"; //和这一句 // 正则解析网页的返回内容 Match match = Regex.Match(response, p); //还有这里 // 取出匹配内容 m_Location = match.Groups["location"].Value.Trim(); //和这里