免费IP归属地API助力网站前端开发

游客2024-06-08 21:57:53

根据IP地址查询归属地信息,支持到中国地区(不含港台地区)区县级别,免费!api地址:

http://city.mimiwuqi.com

永久免费使用~~~

返回数据

免费IP归属地API助力网站前端开发 1

使用方法:

JavaScript (使用Fetch API)

// 使用Fetch API请求你的API并解析返回的JSON数据
fetch('http://city.mimiwuqi.com/')
  .then(response => response.json())
  .then(data => {
    console.log('rovince:', data.province);
    console.log('City:', data.city);
  })
  .catch(error => {
    console.error('Error:', error);
  });

利用js写一个屏蔽城市访问:

        // 定义要屏蔽的城市
        const blockedCity = "Yuncheng";

        // 使用Fetch API请求你的API并解析返回的JSON数据
        fetch('http://city.mimiwuqi.com/')
            .then(response => response.json())
            .then(data => {
                console.log('Province:', data.province);
                console.log('City:', data.city);

                // 检查用户所在城市是否被屏蔽
                if (data.city === blockedCity) {
                    // 禁止访问,重定向到一个错误页面或者显示禁止访问的信息
                    document.getElementById('message').innerText = "Access denied for your location.";
                    // 你可以选择重定向到一个错误页面
                    // window.location.href = 'http://yourdomain.com/access-denied.html';
                } else {
                    document.getElementById('message').innerText = "You are welcome to access this site.";
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('message').innerText = "Unable to determine your location.";
            });


Python (使用requests库)

import requests

# 发送GET请求到API
response = requests.get('http://city.mimiwuqi.com/')
# 解析返回的JSON数据
data = response.json()

print('Province:', data['province'])
print('City:', data['city'])

Java (使用HttpURLConnection)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("http://city.mimiwuqi.com/");
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            
            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            
            // 关闭连接
            in.close();
            con.disconnect();
            
            // 解析JSON响应
            JSONObject json = new JSONObject(content.toString());
            System.out.println("Province: " + json.getString("province"));
            System.out.println("City: " + json.getString("city"));
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}