淘寶 IP 地址庫提供免費 HTTP 介面,回傳 JSON 格式包含國家、地區、城市、ISP 等資訊。請求範例:
https://ip.taobao.com/service/getIpInfo.php?ip=60.214.183.158
回傳:
{
"code": 0,
"data": {
"country": "中國",
"area": "華東",
"region": "山東省",
"city": "東營市",
"isp": "聯通",
"ip": "60.214.183.158"
}
}
package getAddressByIp;
import java.io.*;
import java.net.*;
import net.sf.json.JSONObject;
public class GetAddressByIp {
public static String GetAddressByIp(String IP) {
String result = "";
try {
String jsonStr = getJsonContent("https://ip.taobao.com/service/getIpInfo.php?ip=" + IP);
System.out.println("API 回傳: " + jsonStr);
JSONObject obj = JSONObject.fromObject(jsonStr);
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;
}
private static String getJsonContent(String urlStr) {
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setDoInput(true);
conn.setRequestMethod("GET");
int respCode = conn.getResponseCode();
if (respCode == 200) {
return convertStreamToJson(conn.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private static String convertStreamToJson(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return new String(baos.toByteArray(), "UTF-8");
}
public static void main(String[] args) {
String addr = GetAddressByIp("120.192.182.1");
System.out.println("查詢結果: " + addr);
}
}
json-lib(需 ezmorph、commons-lang、commons-beanutils、commons-collections、commons-logging)。Jackson、Gson 或 Fastjson。setConnectTimeout、setReadTimeout)。code != 0 視為查詢失敗。String location = GetAddressByIp.GetAddressByIp("120.192.182.1");
System.out.println(location); // 輸出:中國--華東--東營市--聯通