Android下客户端获取外网ip

作者: 格吾刚哥 | 来源:发表于2016-12-07 23:53 被阅读788次

    主要原理就是调用外网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;
    
        }
    
    

    相关文章

      网友评论

        本文标题:Android下客户端获取外网ip

        本文链接:https://www.haomeiwen.com/subject/apmjmttx.html