1 /// <summary> 2 3 /// 根据IP获取省市 4 5 /// </summary> 6 7 public void GetAddressByIp() 8 9 { 10 11 string ip = "115.193.217.249"; 12 13 string PostUrl = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=" + ip; 14 15 string res = GetDataByPost(PostUrl);//该条请求返回的数据为:res=1\t115.193.210.0\t115.194.201.255\t中国\t浙江\t杭州\t电信 16 17 18 string[] arr = getAreaInfoList(res); 19 20 }
1 /// <summary> 2 3 /// Post请求数据 4 5 /// </summary> 6 7 /// <param name="url"></param> 8 9 /// <returns></returns> 10 11 public string GetDataByPost(string url) 12 13 { 14 15 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 16 17 string s = "anything"; 18 19 byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(s); 20 21 req.Method = "POST"; 22 23 req.ContentType = "application/x-www-form-urlencoded"; 24 25 req.ContentLength = requestBytes.Length; 26 27 Stream requestStream = req.GetRequestStream(); 28 29 requestStream.Write(requestBytes, 0, requestBytes.Length); 30 31 requestStream.Close(); 32 33 34 HttpWebResponse res = (HttpWebResponse)req.GetResponse(); 35 36 StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default); 37 38 string backstr = sr.ReadToEnd(); 39 40 sr.Close(); 41 42 res.Close(); 43 44 return backstr; 45 46 }
1 /// <summary> 2 3 /// 处理所要的数据 4 5 /// </summary> 6 7 /// <param name="ip"></param> 8 9 /// <returns></returns> 10 11 public static string[] getAreaInfoList(string ipData) 12 13 { 14 15 //1\t115.193.210.0\t115.194.201.255\t中国\t浙江\t杭州\t电信 16 17 string[] areaArr = new string[10]; 18 19 string[] newAreaArr = new string[2]; 20 21 try 22 23 { 24 25 //取所要的数据,这里只取省市 26 27 areaArr = ipData.Split('\t'); 28 29 newAreaArr[0] = areaArr[4];//省 30 31 newAreaArr[1] = areaArr[5];//市 32 33 } 34 35 catch (Exception e) 36 37 { 38 39 // TODO: handle exception 40 41 } 42 43 return newAreaArr; 44 45 }