淘寶提供公開的手機號段查詢介面(https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=),回應為 JavaScript 變數賦值格式,需經處理轉為標準 JSON 後解析。
package com.think.java;
import java.io.*;
import java.net.*;
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestMobileCity {
/** 查詢單一手機號碼歸屬省份 */
public static String calcMobileCity(String mobileNumber) throws MalformedURLException {
String jsonString = null;
JSONArray array = null;
JSONObject jsonObject = null;
String urlString = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobileNumber;
StringBuffer sb = new StringBuffer();
BufferedReader buffer = null;
URL url = new URL(urlString);
try {
InputStream in = url.openStream();
// 淘寶 API 回應編碼為 GB2312
buffer = new BufferedReader(new InputStreamReader(in, "gb2312"));
String line;
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
in.close();
buffer.close();
jsonString = sb.toString();
// 原始回應格式:__GetZoneResult_ = { ... }
// 移除前綴並包裝為 JSON 陣列
jsonString = jsonString.replaceAll("^[__]\\w{14}+[_ = ]+", "[");
String jsonString2 = jsonString + "]";
array = JSONArray.fromObject(jsonString2);
jsonObject = array.getJSONObject(0);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject.getString("province");
}
/** 批次查詢多個號碼 */
public static JSONObject calcMobilesCities(List<String> mobileNumbers) throws MalformedURLException {
JSONObject jsonNumberCity = new JSONObject();
for (String mobileNumber : mobileNumbers) {
jsonNumberCity.put(mobileNumber, calcMobileCity(mobileNumber));
}
return jsonNumberCity;
}
public static void main(String[] args) throws Exception {
// 單一查詢測試
String testMobile = "1881758452";
System.out.println("歸屬地:" + calcMobileCity(testMobile));
// 批次測試
List<String> mobileList = new ArrayList<>();
for (int i = 1350345; i < 1350388; i++) {
mobileList.add(String.valueOf(i));
}
System.out.println("批次結果:" + calcMobilesCities(mobileList).toString());
}
}
gb2312,必須指定 InputStreamReader(in, "gb2312") 避免中文亂碼。__GetZoneResult_ = {province:'北京', ...},使用正則移除前綴並包裝成 [{...}] 供 JSONArray.fromObject() 解析。net.sf.json-lib (json-lib) 處理 JSON,Maven 依賴:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
MalformedURLException、IOException,建議加入超時設定與重試機制。| 欄位 | 說明 | 範例 |
|---|---|---|
| province | 省份 | 北京 |
| city | 城市 | 北京 |
| catName | 運營商 | 中國移動 |
| telString | 查詢號碼 | 1881758452 |
HttpClient 替代 URLConnection 提升併發效能