Java 根据 IP 获取城市编码

引言

在开发中,有时候需要根据用户的 IP 地址来获取用户所在的城市编码。本文将介绍如何使用 Java 实现根据 IP 获取城市编码的功能。

流程图

graph TD;
  A[获取用户 IP] --> B[使用 IP 地址库查询城市编码] --> C[返回城市编码]

步骤说明

  1. 获取用户的 IP 地址
  2. 使用 IP 地址库查询城市编码
  3. 返回城市编码

获取用户 IP

// Import required libraries
import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetUserIP {
    public static String getUserIP() {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            return localhost.getHostAddress().trim();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }
}

上述代码通过使用 java.net.InetAddress 类来获取本机的 IP 地址。InetAddress.getLocalHost() 方法返回一个表示本地主机的 InetAddress 对象,然后可以通过 getHostAddress() 方法获取 IP 地址。

使用 IP 地址库查询城市编码

在实际开发中,我们可以使用第三方的 IP 地址库来查询 IP 地址对应的城市编码。这里以 [ip-api.com]( 为例,该网站提供了免费的 IP 地址查询服务。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetCityCodeByIP {
    public static String getCityCodeByIP(String ip) {
        try {
            // Create URL object with API endpoint
            URL url = new URL(" + ip);
            
            // Establish HTTP connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // Set request method
            connection.setRequestMethod("GET");
            
            // Get response code
            int responseCode = connection.getResponseCode();
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Read response
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                
                in.close();
                
                // Parse JSON response and extract city code
                // Assuming the response format is like {"city":"City Name","code":12345}
                String json = response.toString();
                int startIndex = json.indexOf("\"code\":") + 7;
                int endIndex = json.indexOf(",", startIndex);
                String cityCode = json.substring(startIndex, endIndex);
                
                return cityCode;
            } else {
                // Handle error case
                System.out.println("Error: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
}

上述代码通过创建一个 URL 对象来指定 IP 查询接口的地址,并建立 HTTP 连接。然后发送 HTTP GET 请求并获取响应。如果响应码为 200(HTTP_OK),则读取响应内容并解析 JSON 数据,提取城市编码。

返回城市编码

public class Main {
    public static void main(String[] args) {
        String ip = GetUserIP.getUserIP();
        String cityCode = GetCityCodeByIP.getCityCodeByIP(ip);
        
        if (cityCode != null) {
            System.out.println("City Code: " + cityCode);
        } else {
            System.out.println("Failed to get city code.");
        }
    }
}

上述代码通过调用 GetUserIP.getUserIP() 方法获取用户的 IP 地址,然后调用 GetCityCodeByIP.getCityCodeByIP(ip) 方法根据 IP 地址查询城市编码。最后输出城市编码。

总结

本文介绍了如何使用 Java 实现根据 IP 获取城市编码的功能。通过获取用户的 IP 地址,再使用第三方的 IP 地址库查询城市编码,最后返回城市编码。希望对刚入行的开发者有所帮助。