java應用淘寶API讀寫json完成手機歸屬地查詢功效代碼。本站提示廣大學習愛好者:(java應用淘寶API讀寫json完成手機歸屬地查詢功效代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是java應用淘寶API讀寫json完成手機歸屬地查詢功效代碼正文
普通查詢手機歸屬地內容應當很好用json格局保留,在網上找到了淘寶的歸屬地API,並下了處置json相干的jar包,做了這個手機歸屬地查詢功效
package com.think.java;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestMobileCity {
/**
* 測試手機號碼是來自哪一個城市的,應用淘寶的API
* @param mobileNumber 手機號碼
* @return
* @throws MalformedURLException
*/
public static String calcMobileCity(String mobileNumber) throws MalformedURLException{
String jsonString = null;
JSONArray array = null;
JSONObject jsonObject = null;
String urlString = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobileNumber;
StringBuffer sb = new StringBuffer();
BufferedReader buffer;
URL url = new URL(urlString);
try{
InputStream in = url.openStream();
// 處理亂碼成績
buffer = new BufferedReader(new InputStreamReader(in,"gb2312"));
String line = null;
while((line = buffer.readLine()) != null){
sb.append(line);
}
in.close();
buffer.close();
// System.out.println(sb.toString());
jsonString = sb.toString();
// 調換失落“__GetZoneResult_ = ”,讓它能轉換為JSONArray對象
jsonString = jsonString.replaceAll("^[__]\\w{14}+[_ = ]+", "[");
// System.out.println(jsonString+"]");
String jsonString2 = jsonString + "]";
// 把STRING轉化為json對象
array = JSONArray.fromObject(jsonString2);
// 獲得JSONArray的JSONObject對象,便於讀取array裡的鍵值對
jsonObject = array.getJSONObject(0);
}catch(Exception e){
e.printStackTrace();
}
return jsonObject.getString("province");
}
/**
* 盤算多個號碼的歸屬地
* @param mobileNumbers 號碼列表
* @return
* @throws MalformedURLException
*/
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 testMobileNumber = "1881758452";
System.out.println(calcMobileCity(testMobileNumber));
List<String> mobileList = new ArrayList<String>();
for(int i = 1350345; i < 1350388; i++){
mobileList.add(String.valueOf(i));
}
System.out.println(calcMobilesCities(mobileList).toString());
}
}