Android下客户端获取外网ip

主要原理就是调用外网api接口来抓取结果,代码如下:

public static String GetNetIp()
    {
        URL infoUrl = null;
        InputStream inStream = null;
        try {
            // http://iframe.ip138.com/ic.asp
            // infoUrl = new URL("http://city.ip138.com/city0.asp");
//            infoUrl = new URL("http://ip138.com");
            infoUrl = new URL("http://city.ip138.com/ip2city.asp");

            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            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();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("[");
                Log.d("zph", "" + start);
                int end = strber.indexOf("]", start + 1);
                Log.d("zph", "" + end);
                line = strber.substring(start + 1, end);
//                line = strber.substring(378, 395);
//                line.replaceAll(" ", "");
                return line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,964评论 25 709
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,441评论 18 399
  • 今天是你生日,在前几天你是很期待的,也经常笑容满面。只是到了今天,反而是不开心了。 大概是天气不太好,大家气氛不热...
    柒姻阅读 3,375评论 0 1
  • Is already autumn now. Darkred fallen leaves covered ever...
    llclare阅读 1,733评论 0 0

友情链接更多精彩内容