Android获取外网IP地址

android端获取外网IP这个功能着实费了心思,试了不少方法,终于找到一个合适的。特意分享出来,希望能减少需要这个功能的程序猿们。

这是费尽心思找到的一个接口 ,忍痛分享出来:

//获取IP接口
public final static String GET_IP = "https://ifconfig.co/json";
//修正(2018-06-27):上边的ifconfig国内已经登录不上,查找后重新找到了可用的地址
public final static String GET_IP = "http://ip.chinaz.com/getip.aspx";
public final static String GET_IP = "http://www.3322.org/dyndns/getip";

获取IP值

    //从接口中提取IP
    public static String GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        try {
            infoUrl = new URL(GlobalConfig.GET_IP);
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                JSONObject jsonObject = new JSONObject(strber.toString());
                //从反馈的结果中提取出IP地址
                return jsonObject.getString("ip");
            }
        } catch (Exception e) {
            return "127.0.0.1";
        }
        return "127.0.0.1";
    }

功能简单,但是。。。。分享值得点赞不是?!

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值