我所遇到的问题:
在一个写的安卓APP跑源码项目时到模拟器或者真机上时,直接通过下面代码的方式,调用输出可以直接的获取到外网的IP,但是当我把APP打包了之后,连接WIFi或者使用数据网络将APP运行到真机上获取IP的时候就是获取不到打印为空,很迷惑。也添加了关于网络的3个权限拥有完全的网络访问权限,真机也给了位置信息权限。
new Thread(new Runnable() {
@Override
public void run() {
try {
String ip = IpUtils.GetNetIp();
System.out.println("当前外网IP:"+ip);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
当前有问题的代码:
public class IpUtils {
/**
* 获取外网ip地址的方法2
*
* @return
*/
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
String line = "";
try {
infoUrl = new URL("http://httpbin.org/ip"); //json格式信息的API,使用案例。
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("origin");
// System.out.println("IP:" + line);
} catch (JSONException e) {
e.printStackTrace();
}
}
return line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
}
希望各位大神在上面的代码的基础上修改代码,能让打包之后的App安装在真机上获取输出外网的IP地址 [最好适配多种网络环境(数据网络,WIFI网络,代理网络VPN)的外网IP获取],希望大佬们提点一下作为初学者的小弟,可以帮帮我想一个解决的办法,再次感谢各位大佬,感激不尽!