淘寶提供免費的 IP 地址查詢 API,回傳 JSON 格式包含國家、地區、省份、城市、ISP 等資訊。本文示範使用 Java 原生 HttpURLConnection 呼叫 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
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();
}
| 方案 | 特點 |
|---|---|
| MaxMind GeoIP2 | 商業級精準度,需授權,提供 Java API 與離線資料庫 |
| IP2Location | 付費服務,支援多語言、多格式 |
| 自建 IP 庫 | 下載免費 CSV/資料庫匯入本地,查詢零延遲、無限制 |
| 高德/騰訊/百度地圖 API | 國內主流地圖服務商提供 IP 定位,需申請 Key |