1 using System; 2 using System.IO; 3 using System.Net; 4 using System.Text; 5 using System.Web.Script.Serialization; 6 7 namespace IpUtils 8 { 9 public class IpDetail 10 { 11 public String Ret { get; set; } 12 13 public String Start { get; set; } 14 15 public String End { get; set; } 16 17 public String Country { get; set; } 18 19 public String Province { get; set; } 20 21 public String City { get; set; } 22 23 public String District { get; set; } 24 25 public String Isp { get; set; } 26 27 public String Type { get; set; } 28 29 public String Desc { get; set; } 30 } 31 32 public class IpHelper 33 { 34 /// <summary> 35 /// 获取IP地址的详细信息,调用的借口为 36 /// http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={ip} 37 /// </summary> 38 /// <param name="ipAddress">请求分析得IP地址</param> 39 /// <param name="sourceEncoding">服务器返回的编码类型</param> 40 /// <returns>IpUtils.IpDetail</returns> 41 public static IpDetail Get(String ipAddress,Encoding sourceEncoding) 42 { 43 String ip = string.Empty; 44 if(sourceEncoding==null) 45 sourceEncoding = Encoding.UTF8; 46 using (var receiveStream = WebRequest.Create("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ipAddress).GetResponse().GetResponseStream()) 47 { 48 using (var sr = new StreamReader(receiveStream, sourceEncoding)) 49 { 50 var readbuffer = new char[256]; 51 int n = sr.Read(readbuffer, 0, readbuffer.Length); 52 int realLen = 0; 53 while (n > 0) 54 { 55 realLen = n; 56 n = sr.Read(readbuffer, 0, readbuffer.Length); 57 } 58 ip = sourceEncoding.GetString(sourceEncoding.GetBytes(readbuffer, 0, realLen)); 59 } 60 } 61 return !string.IsNullOrEmpty(ip)?new JavaScriptSerializer().Deserialize<IpDetail>(ip):null; 62 } 63 } 64 65 public class EncodingHelper 66 { 67 public static String GetString(Encoding source, Encoding dest, String soureStr) 68 { 69 return dest.GetString(Encoding.Convert(source, dest, source.GetBytes(soureStr))); 70 } 71 72 public static String GetString(Encoding source, Encoding dest, Char[] soureCharArr, int offset, int len) 73 { 74 return dest.GetString(Encoding.Convert(source, dest, source.GetBytes(soureCharArr, offset, len))); 75 } 76 } 77 }
.NET技术交流群 199281001 .欢迎加入。