Java获取IP地址及对应的归属地
    		       		warning:
    		            这篇文章距离上次修改已过434天,其中的内容可能已经有所变动。
    		        
        		                
                在Java中,获取IP地址及其归属地可以通过外部服务API实现。一个常用的API是ip-api.com。以下是一个简单的Java代码示例,使用了java.net包中的URL和URLConnection类来发送HTTP请求,并解析返回的JSON数据以获取IP地址的归属地信息。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
 
public class IPLookup {
 
    public static void main(String[] args) {
        String ip = "123.123.123.123"; // 替换为要查询的IP地址
        String urlString = "http://ip-api.com/json/" + ip;
 
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
 
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
 
            // 解析JSON以获取归属地信息
            JSONObject jsonObject = new JSONObject(response.toString());
            String country = jsonObject.getString("country");
            System.out.println("IP: " + ip + " is from " + country);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}确保你有json.org的JSON处理库在classpath中,或者使用其他JSON处理库如Gson或Jackson。
注意:ip-api.com是一个免费服务,可能会有请求频率限制。对于商业用途,可能需要使用付费的API服务或者其他提供相同功能的API服务。
评论已关闭