網上有不少獲取IP的例子,不過都是獲取到的本地ip,還有的是由於走不通了,獲取到的ip爲空,下面看實測獲取到外網IP的代碼,注意須要在線程裏面執行json
/** * 獲取外網的IP(要訪問Url,要放到後臺線程裏處理) * * @param @return * @return String * @throws * @Title: GetNetIp * @Description: */ public static String getNetIp() { URL infoUrl = null; InputStream inStream = null; String ipLine = ""; HttpURLConnection httpConnection = null; try { // infoUrl = new URL("http://ip168.com/"); infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8"); URLConnection connection = infoUrl.openConnection(); 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"); } Pattern pattern = Pattern .compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))"); Matcher matcher = pattern.matcher(strber.toString()); if (matcher.find()) { ipLine = matcher.group(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { inStream.close(); httpConnection.disconnect(); } catch (IOException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } Log.e("getNetIp", ipLine); return ipLine; }