java 通过ip获取地理地址
时间: 2023-11-27 07:02:23 浏览: 48
要通过IP地址获取地理地址,可以使用第三方的IP地址查询API或者使用Java内置的InetAddress类的方法。
使用第三方API可以使用如下代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class IPUtil {
private static final String URL_TEMPLATE = "http://ip.taobao.com/service/getIpInfo.php?ip=%s";
public static String getAddressByIp(String ip) {
try {
URL url = new URL(String.format(URL_TEMPLATE, ip));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
connection.disconnect();
String result = stringBuilder.toString();
JSONObject jsonObject = JSONObject.parseObject(result);
if (jsonObject.getIntValue("code") == 0) {
JSONObject data = jsonObject.getJSONObject("data");
return data.getString("country") + data.getString("region") + data.getString("city");
}
} catch (Exception e) {
e.printStackTrace();
}
return "未知地址";
}
}
```
如果你不想使用第三方API,可以使用Java内置的InetAddress类来完成。示例代码如下:
```java
import java.net.InetAddress;
public class IPUtil {
public static String getAddressByIp(String ip) {
try {
InetAddress inetAddress = InetAddress.getByName(ip);
return inetAddress.getHostName();
} catch (Exception e) {
e.printStackTrace();
}
return "未知地址";
}
}
```
这里返回的是主机名,可以根据主机名自行解析地址信息。