2014-05-22 73 views
1

您好我试着写一个程序,我可以从http://ifconfig.me/ip获得一个字符串从网站

得到我的公网IP地址,但我的代码失败..程序编译,但是当我按下按钮获得ip和显示它的程序被冻结我曾尝试下面的代码

using system.xml; 
XmlDocument document = new XmlDocument(); 
document.Load("http://ifconfig.me/ip"); 
string allText = document.InnerText; 

和我的其他代码是

using system.net 
WebClient abc = new WebClient(); 
txtMyIp.Text = abc.DownloadString("http://www.ifconfig.me/ip"); 

任何一个可以告诉我,为什么程序FR一txtbox当我按下按钮时会感觉到吗?或者建议我使用其他方式/方法?

btw我正在使用visual studio 2012

+1

*但这两个代码都失败*它们究竟有多失败? –

+0

失败我的意思是他们编译,但他们什么都不做,当按钮被点击程序冻结时 – Licentia

+0

这是重要的信息,冻结是不一样的什么都不做 –

回答

1
  1. 你的UI冻结,因为你的网站在UI线程,这意味着你的UI线程只能等待unitl您abc.DownloadString("http://www.ifconfig.me/ip");执行下载的字符串。 基于此,我建议您使用异步/等待和HttpClientSystem.Net.Http。您的代码应该是这样的:

    ​​
  2. 请注意,您可以通过调用abc.DownloadStringTaskAsync(uri)做同样的WebClient,但HttpClient应该是更快,因为它不包含网络浏览器的模拟像WebClient相关的东西。
  3. 另请注意,对于这两种API,您应该通过将其包装在使用语句中来处理客户端,因为它必须释放一些资源,例如关闭为传入数据打开的流。
  4. 如果您正在使用的版本的.NET Framework小于4.5,并且希望使用Web客户端 - 试试这个代码片段,它不应该冻结您的UI:

    private void button1_Click(object sender, EventArgs e) 
    { 
        using (var abc = new WebClient()) 
        { 
         var uri = new Uri(@"http://www.ifconfig.me/ip"); 
         abc.DownloadStringCompleted += (o, args) => txtMyIp.Text = args.Result; 
         abc.DownloadStringAsync(uri); 
        } 
    } 
    
  5. 我注意到,有时http://www.ifconfig.me/ip返回永久重定向到http://ifconfig.me/ip,因此我认为你应该使用没有www的地址。
3

这是网站,导致这样做。它只是需要很长时间才能加载。 你应该尝试使用其他网站:http://wtfismyip.com/text 我试过

string myIP = new WebClient().DownloadString("http://wtfismyip.com/text"); 

它工作得很好。

+0

试试[WhatsMyIp](http://www.whatsmyip.org/)。它比你试图屏蔽的那个要快得多。 – Icemanind

1

的另一种方法:

using System.IO; 
using System.Net; 

String url = "http://ifconfig.me/ip"; 
String responseFromServer = null; 
try 
{ 
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    if (response.StatusCode == HttpStatusCode.OK) 
    { 
     using (Stream dataStream = response.GetResponseStream()) 
     { 
      using (StreamReader reader = new StreamReader(dataStream)) 
       responseFromServer = reader.ReadToEnd(); 
     } 
    } 
} 
catch { } 

if (!String.IsNullOrEmpty(responseFromServer)) 
    MessageBox.Show(responseFromServer); 
1

在LINQPad试过成功(记得要加System.Net命名空间):

void Main() 
{ 
    var client = new WebClient(); 
    Console.WriteLine(client.DownloadString("http://www.ifconfig.me/ip")); 
} 

结果:

177.156.151.233 

PS: Linqpad :https://www.linqpad.net/

0

你应该尝试异步下载的字符串:

Uri uri = new Uri("http://ifconfig.me/ip"); 
XmlDocument xmlDocument = await XmlDocument.LoadFromUriAsync(uri); 
string result = xmlDocument.ToString();