/** * 获取公网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; }
使用时要开辟线程,不然会奔溃
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦