當今購物、旅游等服務型的網站如此流行,我們有時候也會碰到這樣網站的開發。
在開發此類網站時,為了增加用戶的體驗感受,我們不得不在用戶剛進入網站時定位到用戶所在地,
更好的為用戶推薦當地產品。比如去哪兒,攜程,美團等都會有定位功能。
那么我們怎樣“貼心”的為用戶定位呢?
1.首先我們需要先獲取本機的外網ip
/**
* 得到本機的外網ip,出現異常時返回空串""
* @return
*/
public static String getPublicIP() {
String ip = "";
org.jsoup.nodes.Document doc = null;
Connection con = null;
con = Jsoup.connect("http://www.ip138.com/ip2city.asp").timeout(10000);
try {
doc = con.get();
// 獲得包含本機ip的文本串:您的IP是:[xxx.xxx.xxx.xxx]
org.jsoup.select.Elements els = doc.body().select("center");
for (org.jsoup.nodes.Element el : els) {
ip = el.text();
}
// 從文本串過濾出ip,用正則表達式將非數字和.替換成空串""
ip = ip.replaceAll("[^0-9.]", "");
} catch (IOException e) {
e.printStackTrace();
}
return ip;
}
2.定義一個方法,將字符拼接成字符串
private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); }
3.將URL資源解析成json對象
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = null; try { is = new URL(url).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { //關閉輸入流 is.close(); } }
4.獲取當地地址名,這個可以根據自己的具體需求更改。參數ak后面的值是ip定位api服務的密鑰,
這個可以自己去百度申請,詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
public static String getAddrName() throws JSONException, IOException{ //這里調用百度的ip定位api服務 詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip="+getPublicIP()); /* 獲取到的json對象: * {"address":"CN|河北|保定|None|UNICOM|0|0", * "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307}, * "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}}, * "status":0} */
//這里我們可以輸出json看一下具體格式
System.out.println(json.toString());
JSONObject content=json.getJSONObject("content"); //獲取json對象里的content對象 JSONObject addr_detail=content.getJSONObject("address_detail");//從content對象里獲取address_detail String city=addr_detail.get("city").toString(); //獲取市名,可以根據具體需求更改,如果需要獲取省份的名字,可以把“city”改成“province”... return city; }
5.這里我們寫一個主方法方便於測試
public static void main(String[] args) throws IOException, JSONException { System.out.println(getAddrName()); }
運行結果: