当前位置:首页 > 安卓源码 > 技术博客 >

Android获取手机外网IP

时间:2017-08-28 22:15 来源:互联网 作者:源码搜藏 浏览: 收藏 挑错 推荐 打印

/** * 获取公网ip(要访问Url,要放到后台线程里处理) * * @return */ public static String getNetIp () { URL infoUrl = null; InputStream inStream = null; String line = ; try { infoUrl = new URL ( http://pv.sohu.com/cityjson?ie=utf-8 ) ; URLConn
/**
 * 获取公网ip(要访问Url,要放到后台线程里处理)
 *
 * @return
 */
public static String getNetIp() {
    URL infoUrl = null;
    InputStream inStream = null;
    String line = "";
    try {
        infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
        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();
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            // 从反馈的结果中提取出IP地址
            int start = strber.indexOf("{");
            int end = strber.indexOf("}");
            String json = strber.substring(start, end + 1);
            if (json != null) {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    line = jsonObject.optString("cip");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i("test", line);
    return line;

}

使用时要开辟线程,不然会奔溃
Android获取手机外网IP 转载https://www.codesocang.com/appboke/36515.html

技术博客阅读排行

最新文章