Android获取外部IP

Lau*_*ura 1 ip android external

我正在开发Android 2.1中的应用程序,我想显示外部IP.我怎么能这样做?提前致谢.

Sul*_*dat 14

public void getCurrentIP () {
    ip.setText("Please wait...");  
    try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://ifcfg.me/ip");
            // HttpGet httpget = new HttpGet("http://ipecho.net/plain");
            HttpResponse response;

            response = httpclient.execute(httpget);

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

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                    long len = entity.getContentLength();
                    if (len != -1 && len < 1024) {
                            String str=EntityUtils.toString(entity);
                            //Log.i("externalip",str);
                ip.setText(str);
                    } else {
                            ip.setText("Response too long or error.");
                            //debug
                            //ip.setText("Response too long or error: "+EntityUtils.toString(entity));
                            //Log.i("externalip",EntityUtils.toString(entity));
                    }            
            } else {
                    ip.setText("Null:"+response.getStatusLine().toString());
            }

    }
    catch (Exception e)
    {
        ip.setText("Error");
    }

}
Run Code Online (Sandbox Code Playgroud)