百度地圖開放平台提供 IP 定位服務,通過 HTTP GET 請求即可獲取 IP 對應的城市、經緯度等信息。本文演示 Java 原生 HttpURLConnection + org.json 解析的完整調用流程,含 AK 申請、參數構建、異常處理、結果映射。
javax.json / JsonParser JDK 11+)。<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
https://api.map.baidu.com/location/ipak (您的 AK)、ip (目標 IP,可選,默認自動獲取調用方 IP)。status (0 成功)、content.address (詳細地址)、content.point (經緯度)、content.city (城市名)。import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class BaiduIpLocationClient {
private static final String API_URL = "https://api.map.baidu.com/location/ip";
private static final String AK = "您的AK"; // 替換為真實 AK
public static void main(String[] args) {
try {
String ip = "202.198.16.3"; // 測試 IP,可為 null 使用自動檢測
JSONObject result = getLocation(ip);
if (result != null) {
System.out.println("完整響應: " + result.toString(2));
System.out.println("地址: " + result.getJSONObject("content").getString("address"));
System.out.println("城市: " + result.getJSONObject("content").getString("city"));
System.out.println("經緯度: " + result.getJSONObject("content").getJSONObject("point").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static JSONObject getLocation(String ip) throws IOException {
StringBuilder urlBuilder = new StringBuilder(API_URL).append("?ak=").append(AK);
if (ip != null && !ip.isEmpty()) {
urlBuilder.append("&ip=").append(ip);
}
HttpURLConnection conn = null;
try {
URL url = new URL(urlBuilder.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("Accept", "application/json");
int code = conn.getResponseCode();
if (code != 200) {
throw new IOException("HTTP 錯誤碼: " + code);
}
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
JSONObject json = new JSONObject(response.toString());
if (json.getInt("status") != 0) {
throw new IOException("API 業務錯誤: " + json.getString("message"));
}
return json;
}
} finally {
if (conn != null) conn.disconnect();
}
}
}
public class BaiduLocationResult {
private int status;
private String message;
private Content content;
public static class Content {
private String address;
private String city;
private String cityCode;
private Point point;
// Getter/Setter
}
public static class Point {
private double x; // 經度
private double y; // 緯度
// Getter/Setter
}
// Getter/Setter
}
// 使用 Jackson/Gson 直接反序列化
// BaiduLocationResult result = objectMapper.readValue(jsonStr, BaiduLocationResult.class);
| status | 含義 | 處理 |
|---|---|---|
| 0 | 成功 | 正常解析 content |
| 1 | 服務器內部錯誤 | 重試/告警 |
| 2 | 請求參數非法 | 檢查 ak/ip 格式 |
| 3 | 權限驗證失敗 | AK 無效/額度耗盡/未綁定服務 |
| 4 | 配額超限 | 緩存/升級配額/降級 |
| 5 | AK 不存在 | 檢查 AK 拼寫 |
百度 IP 定位 API 調用極其簡單,核心在於「AK 管理、超時設置、錯誤碼處理、高併發優化」。生產環境務必引入 HTTP 客端連接池、本地緩存與熔斷機制,確保服務穩定性。若需更高精度 (街道級),可結合瀏覽器 Geolocation API (前端獲取經緯度) 反向地理編碼,實現多源定位融合。