呼叫第三方API ,實現手機號碼歸屬地及運營商查詢
阿新 • • 發佈:2019-01-26
執行結果:
中國電信
西雙版納
西雙版納,中國電信
程式碼:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class NewMobile { public static void main(String[] args) { System.out.println(NewMobile.getCarrier("18988176532")); System.out.println(NewMobile.getCity("18988176532")); System.out.println(NewMobile.getResult("18988176532")); } //得到歸屬地 public static String getCity(String tel) { try{ //獲取返回結果 String json = httpRequest(tel).toString(); //拆分xml頁面程式碼 String[] a = json.split("att"); String[] b = a[1].split(","); //歸屬地 String city = b[2].replace(">", "").replace("</", ""); return city; }catch(Exception e){ return "暫無相關歸屬地資訊!"; } } //得到運營商 public static String getCarrier(String tel) { try{ //獲取返回結果 String json = httpRequest(tel).toString(); //拆分xml頁面程式碼 String[] a = json.split("att"); String[] c = a[2].split("operators"); //運營商 String carrier = c[1].replace(">", "").replace("</", ""); return carrier; }catch(Exception e){ return "暫無相關運營商資訊!"; } } //得歸屬地,運營商。如:西雙版納,中國電信 public static String getResult(String tel) { try{ //獲取返回結果 String json = httpRequest(tel).toString(); //拆分xml頁面程式碼 String[] a = json.split("att"); String[] b = a[1].split(","); //歸屬地 String city = b[2].replace(">", "").replace("</", ""); String[] c = a[2].split("operators"); //運營商 String carrier = c[1].replace(">", "").replace("</", ""); String cityAndCarrier = city+","+carrier; return cityAndCarrier; }catch(Exception e){ return "暫無相關歸屬地、運營商資訊!"; } } /** * 發起http請求獲取返回結果 * @param tel 待查詢手機號 * @return String 結果字串 */ public static String httpRequest(String tel) { //組裝查詢地址(requestUrl 請求地址) String requestUrl = "http://api.k780.com:88/?app=phone.get&phone="+tel+"&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=xml"; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(false); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestMethod("GET"); httpUrlConn.connect(); //將返回的輸入流轉換成字串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); //釋放資源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); } catch (Exception e) { return "發起http請求後,獲取返回結果失敗!"; } return buffer.toString(); } }