android - 我怎样才能得到我的外部/IP?

标签 android http ip

<分区>

Possible Duplicate:
How to get ip address of the device?

下面是我如何尝试获取外部 IP 的 fragment 。然而,它没有返回任何东西......

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;

}

最佳答案

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;
}

2015 年 2 月更新

WhatIsMyIp 现在公开一个 developer API你可以使用。

关于android - 我怎样才能得到我的外部/IP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12854399/

相关文章:

android - 在运行时更改应用程序主题

python - 检查 s3 url 是否存在

Azure 门户 IP 配置无法修改 VM 的 DNS 名称

API 或属于云提供商的所有 IP 范围的可下载列表

java - Listview 滚动时滞后,添加项目时崩溃

android - 在相机和图库之间进行选择以进行图像选择

c++ - 对维基百科的 HTTP 请求

c# - 如何通过我的 Visual Studio 访问 Google 项目 [.Net]?

php - php wordpress 根据非本地IP地址条件隐藏特定导航项

java - 蓝牙连接错误