继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

获取手机外网IP

繁星淼淼
关注TA
已关注
手记 149
粉丝 44
获赞 263
/**
 * 获取公网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;

}

使用时要开辟线程,不然会奔溃

原文链接:http://www.apkbus.com/blog-867211-68759.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP