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;

    }

    原文作者:格吾刚哥
    原文地址: https://www.jianshu.com/p/7bcfc2a80f12
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞