gpt4 book ai didi

java - 如何使用IP获取国家代码和国家名称

转载 作者:行者123 更新时间:2023-11-30 01:03:03 28 4
gpt4 key购买 nike

我是 android 的新手,我想使用 ip 地址获取国家名称和国家代码。请任何人指导我。

获取IP的代码如下:

public String getLocalIpAddress() {
WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(context.WIFI_SERVICE);
if(wifiMgr.isWifiEnabled()) {
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String wifiIpAddress = String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));

return wifiIpAddress;
}else{
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i("","111 inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
//the condition after && is missing in your snippet, checking instance of inetAddress
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
Log.i("","111 return inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}

}
}
} catch (SocketException e) {
e.printStackTrace();
}
}

return null;
}

我不知道如何使用 IP 地址获取国家代码和名称。

提前致谢!

最佳答案

1.) 查询您的公共(public) ip 地址:

public static String getPublicIP() throws IOException
{
Document doc = Jsoup.connect("http://www.checkip.org").get();
return doc.getElementById("yourip").select("h1").first().select("span").text();
}

2.) 然后查询你的国家代码/名字:(用上面的方法)

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://ipinfo.io/"+getPublicIP());
HttpResponse response;
try {
response = client.execute(request);

Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

希望对您有所帮助。

关于java - 如何使用IP获取国家代码和国家名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39206727/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com