WinForm-WebClient 类的公共方法

从MSDN的定义看 :WebClient类提供向任何URI标识的本地、Intranet(内网)、Internet 资源发送数据和接收数据的公共方法。

我们将从一个比较长的实例来认识WebClient的用法。程序100多行,且没注释。但后续会添加上去的。

本实例是通过对Ip138 以及 taobao 提供的API进行调用,从而获得外网ip以及ip归属地的方法。

首先是用到的三个函数:

 1 ///获得外网IP地址,由于学校是在局域网。所以比较麻烦

 2 private static string GetIPAddress()

 3 {

 4     string tempip = "";

 5     try

 6         {

 7              WebRequest wr = WebRequest.Create("http://www.ip138.com/ip2city.asp");

 8                 Stream s = wr.GetResponse().GetResponseStream();

 9                 StreamReader sr = new StreamReader(s, Encoding.Default);

10                 string all = sr.ReadToEnd(); //读取网站的数据

11 

12                 int start = all.IndexOf("[") + 1;

13                 int end = all.IndexOf("]", start);

14                 tempip = all.Substring(start, end - start);

15                 sr.Close();

16                 s.Close();

17     }

18     catch

19     {

20     }

21     return tempip;

22 }
 1 ///根据获得的外网IP 从而获得IP归属地信息

 2 public void ThreadProc(string ip)

 3         {

 4             if (!IsVaildIPAddress(ip))

 5             {

 6                 MessageBox.Show("Illegal", "Error", MessageBoxButtons.OK,

 7         MessageBoxIcon.Error);

 8             }

 9             WebClient client = new WebClient();

10             string uri = @"http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;

11             string jsonData = client.DownloadString(uri);
         //下面语句需要引用Json.dll
12 IPCheckResult result = JsonConvert.DeserializeObject<IPCheckResult> 13 (jsonData); 14 if (result.code != 0) 15 { 16 MessageBox.Show("Not Found"); 17 } 18 textBox1.Text = result.data.Region; 19 textBox2.Text = result.data.City; 20 textBox3.Text = result.data.Country + result.data.ISP; 21 textBox4.Text = result.data.Area + "地区"; 22 }
///用正则表达式 验证IP

private bool IsVaildIPAddress(string ip)

        {

            string pattern = @"^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))$";

            return Regex.IsMatch(ip, pattern);

        }
///Form_Load事件调用
1
private void Form1_Load(object sender, EventArgs e) 2 { 3 string ip = GetIPAddress(); 4 Thread thread = new Thread(() => ThreadProc(ip));
        //始终觉得 Lamda表达式是线程调用有参数的函数的好办法。。。。
5 thread.Start(); 6 }

 

最后是用到的两个自定义类:

 1 namespace IPAddress

 2 {

 3     class IPAddressData

 4     {

 5         public string Country;//获取IP所在城市

 6         public string Area;//获取IP所在地区

 7         public string Region;//获取IP所在省

 8         public string City;//获取IP所在市

 9         public string ISP;//获取IP所属运营商

10         public IPAddressData()

11         { }

12     }

13 }
1 namespace IPAddress

2 {

3     class IPCheckResult

4     {

5         public int code;

6         public IPAddressData data;

7     }

8 }

程序结果:

WinForm-WebClient 类的公共方法

至于程序跑起来遇到的从不是创建控件的线程访问控件,看官们 百度一下就行。有几种解决方法。(●'◡'●)

 

你可能感兴趣的:(WinForm)