话不多说,直接代码,记录一下,希望可以帮到需要的朋友:
//获取外网
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
try {
infoUrl = new URL("http://ip.chinaz.com/getip.aspx");
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地址
String objStr = strber.toString();
try {
JSONObject object = new JSONObject(objStr);
line = object.getString("ip");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}