首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 呼叫淘寶 IP 地址庫 API 查詢地理位置

     編輯:Java 程式設計入門

淘寶提供免費的 IP 地址查詢 API,回傳 JSON 格式包含國家、地區、省份、城市、ISP 等資訊。本文示範使用 Java 原生 HttpURLConnection 呼叫 API 並解析回應。

API 介面說明

請求 URL:https://ip.taobao.com/service/getIpInfo.php?ip=IP地址

回應範例:

{
  "code": 0,
  "data": {
    "country": "中國",
    "country_id": "CN",
    "area": "華東",
    "area_id": "300000",
    "region": "山東省",
    "region_id": "370000",
    "city": "東營市",
    "city_id": "370500",
    "county": "",
    "county_id": "-1",
    "isp": "聯通",
    "isp_id": "100026",
    "ip": "60.214.183.158"
  }
}

code=0 表示成功,非零表示查詢失敗(如 IP 格式錯誤、頻率限制等)。

完整實作程式碼

package getAddressByIp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;

public class GetAddressByIp {

    /** 
     * 根據 IP 查詢地理位置
     * @param ip IP 位址字串
     * @return 格式化地址字串,失敗回傳錯誤訊息
     */
    public static String getAddressByIp(String ip) {
        String result = "";
        try {
            String json = getJsonContent("https://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
            System.out.println("API 回應: " + json);
            
            JSONObject obj = JSONObject.fromObject(json);
            String code = obj.getString("code");
            
            if ("0".equals(code)) {
                JSONObject data = obj.getJSONObject("data");
                result = data.getString("country") + "--" 
                       + data.getString("area") + "--" 
                       + data.getString("city") + "--" 
                       + data.getString("isp");
            } else {
                result = "IP 地址有誤或查詢失敗";
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "獲取 IP 地址異常: " + e.getMessage();
        }
        return result;
    }
    
    /** 發送 HTTP GET 請求並取得 JSON 回應 */
    private static String getJsonContent(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            
            // 連線設定
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                return convertStreamToJson(conn.getInputStream());
            } else {
                System.err.println("HTTP 錯誤碼: " + responseCode);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /** 將 InputStream 轉為字串 */
    private static String convertStreamToJson(InputStream inputStream) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return new String(out.toByteArray(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    
    public static void main(String[] args) {
        String addr = GetAddressByIp.getAddressByIp("120.192.182.1");
        System.out.println("查詢結果: " + addr);
    }
}

依賴需求

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

或改用現代 JSON 函式庫(Jackson、Gson、Fastjson)替換 net.sf.json。

現代化改寫建議(Java 11+ HttpClient + Jackson)

// Java 11+ HttpClient
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://ip.taobao.com/service/getIpInfo.php?ip=" + ip))
    .timeout(Duration.ofSeconds(3))
    .GET()
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode root = new ObjectMapper().readTree(response.body());
if (root.path("code").asInt() == 0) {
    JsonNode data = root.path("data");
    return data.path("country").asText() + " " + data.path("region").asText() + " " + data.path("city").asText();
}

使用限制與注意事項

  • 頻率限制:淘寶 API 有 QPS 限制,大量查詢需自建 IP 庫或採購商業服務
  • 僅支援 HTTP:未提供 HTTPS,敏感環境請評估安全性
  • 資料準確度:免費版資料更新頻率較低,精確度不如商業 IP 庫
  • 編碼處理:回應為 UTF-8,讀取流時需指定字集避免中文亂碼
  • 異常處理:網路超時、API 變更、JSON 解析失敗皆需完善處理

替代方案

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方案特點
MaxMind GeoIP2商業級精準度,需授權,提供 Java API 與離線資料庫
IP2Location付費服務,支援多語言、多格式
自建 IP 庫下載免費 CSV/資料庫匯入本地,查詢零延遲、無限制
高德/騰訊/百度地圖 API國內主流地圖服務商提供 IP 定位,需申請 Key