java通过ip获取ip归属地
时间: 2023-11-27 12:05:10 浏览: 40
Java可以通过调用第三方IP库来实现通过IP地址获取IP归属地的功能。下面是一个使用淘宝IP库的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.alibaba.fastjson.JSONObject;
public class IpUtil {
/**
* 通过 IP 地址获取地址信息
*
* @param ip IP 地址,例如:192.168.0.1
* @return 地址信息,例如:中国|0|北京|北京市|联通
*/
public static String getAddressInfo(String ip) {
String result = "";
try {
// 淘宝IP库API接口
String apiurl = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
URL url = new URL(apiurl);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
} catch (Exception e) {
System.out.println("Error in getting IP address information: " + e.getMessage());
}
return result;
}
public static void main(String[] args) {
String addressInfo = getAddressInfo("112.80.248.75");
JSONObject jsonObject = JSONObject.parseObject(addressInfo);
if (jsonObject.getIntValue("code") == 0) {
JSONObject data = jsonObject.getJSONObject("data");
System.out.println(data.getString("country"));
System.out.println(data.getString("region"));
System.out.println(data.getString("city"));
} else {
System.out.println("Error in getting IP address information: " + jsonObject.getString("msg"));
}
}
}
```
上述代码中的`getAddressInfo`方法使用了淘宝IP库的API接口来获取IP地址的归属地信息。其中,`jsonObject.getIntValue("code") == 0`表示查询成功,`data`是一个JSON对象,里面包含了`country`、`region`和`city`等地址信息字段。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)