2012-10-12 150 views
1

可能重複:
How to get ip address of the device?我如何獲得我的外部/ IP?

下面是如何我試圖讓外部IP片段。但是,它不返回任何東西......

public String getIpAddress() { 

    try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpGet httpget = new HttpGet("http://www.whatismyip.com/?404"); 
      // HttpGet httpget = new HttpGet("http://whatismyip.com.au/"); 
      // HttpGet httpget = new HttpGet("http://www.whatismyip.org/"); 
      HttpResponse response; 

      response = httpclient.execute(httpget); 

      //Log.i("externalip",response.getStatusLine().toString()); 

      HttpEntity entity = response.getEntity(); 
      entity.getContentLength(); 
      str = EntityUtils.toString(entity); 
    } 
    catch (Exception e) 
    { 
    } 
    return str; 

} 
+0

日誌貓在哪裏? –

回答

11
public String getIpAddress() { 
String ip; 
    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON"); 
     // HttpGet httpget = new HttpGet("http://whatismyip.com.au/"); 
     // HttpGet httpget = new HttpGet("http://www.whatismyip.org/"); 
     HttpResponse response; 

     response = httpclient.execute(httpget); 
     //Log.i("externalip",response.getStatusLine().toString()); 

     HttpEntity entity = response.getEntity(); 
     entity.getContentLength(); 
     str = EntityUtils.toString(entity); 
     Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show(); 
     JSONObject json_data = new JSONObject(str); 
     ip = json_data.getString("ip"); 
     Toast.makeText(getApplicationContext(), ip, Toast.LENGTH_LONG).show(); 
    } 
    catch (Exception e){...} 

    return ip; 
} 

OR

UPDATE 2015年2月

WhatIsMyIp現在公開您可以使用的developer API

+0

<使用權限android:name =「android.permission.INTERNET」/> –

+0

謝謝!!!! ..從今天早上一直卡在這裏.. IT終於工作...:= – omi0301

+0

隨時問我。 android - php的問題。謝謝 –

相關問題