前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
運行結果:
中國電信
西雙版納
西雙版納,中國電信
代碼:
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();}
}
?