java根據手機號獲取歸屬地
阿新 • • 發佈:2019-02-01
引言
最近在做一個關於車新聞的專案,讓弄個根據使用者註冊的手機號獲取該使用者手機號所在地區,剛剛聽說感覺特別高大上,這也可以獲得???於是就開始度娘。。查了好多資料漸漸的明白了原理。
原理介紹
(1)先上網差一些能夠查詢手機號獲取歸屬地的API地址。(推薦地址:http://blog.csdn.net/liuyunfan/article/details/13624335)裡面有很多API。例如:http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile=手機號碼&amount=10000&callname=getPhoneNumInfoExtCallback
從網頁裡面瀏覽如圖:
(2)利用java url.openstream獲取URL(API地址)頁面的全部內容。
(3)把獲取的內容去掉一些沒有用的東西轉換成json結構。
(4)獲取json結構中需要的城市的value值。
程式碼示例
用的話直接呼叫這個方法就可以了。<span style="color:#6666cc;font-weight: bold;"> </span>/** * 測試手機號碼是來自哪個城市的,利用拍拍網的API * @param mobileNumber 手機號碼 * @return * @throws MalformedURLException */ public static String calcMobileCity(String mobileNumber) throws MalformedURLException{ String jsonString = null; JSONArray array = null; JSONObject jsonObject = null; //獲取拍拍網的API地址 String urlString = "http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile="+mobileNumber+"&amount=10000&callname=getPhoneNumInfoExtCallback"; StringBuffer sb = new StringBuffer(); BufferedReader buffer; URL url = new URL(urlString); try{ //獲取URL地址中的頁面內容 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(); // 替換掉“getPhoneNumInfoExtCallback(,);<!--[if !IE]>|xGv00|6741027ad78d9b06f5642b25ebcb1536<![endif]-->”,讓它能轉換為JSONArray物件 jsonString = jsonString.replace("getPhoneNumInfoExtCallback(", "["); jsonString = jsonString.replace(");<!--[if !IE]>|xGv00|6741027ad78d9b06f5642b25ebcb1536<![endif]-->", "]"); // 把jsonString轉化為json物件 array = JSONArray.fromObject(jsonString); // 獲取JSONArray的JSONObject物件,便於讀取array裡的鍵值對 jsonObject = array.getJSONObject(0); }catch(Exception e){ e.printStackTrace(); } //從JSONObject物件中讀取城市名稱 return jsonObject.getString("cityname"); }<span style="color:#6666cc;font-weight: bold;"> </span>
呼叫結果
列印到控制檯如圖:
結束語
不要被困難嚇倒,不要因沒有聽過,沒有做過的事情而退縮。勇往直前你會發現其實都很簡單。。。