任務需要,希望根據一組ip地址來獲取其真實所在地。
忽然想起來之前使用百度的服務是可以通過ip地址查詢真實地址的,於是迅速在百度的搜索頁中找到了這個小工具。發現百度通過調用www.ip138.com/這個網站的服務來獲取真實地址。

在輸入欄輸入查詢按鈕,並點擊查詢按鈕,發現這個查詢服務是通過ajax實現的,請求的地址是 https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=123.123.192.255&co=&resource_id=6006&t=1433922612109&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110206955700272228569_1433922418817&_=1433922418822
返回的信息數據如下:
/**/jQuery110206955700272228569_1433922418817({"status":"0","t":"1433922612109","set_cache_time":"","data":[{"location":"北京市 聯通", "titlecont":"IP地址查詢", "origip":"123.123.192.255", "origipquery":"123.123.192.255", "showlamp":"1", "showLikeShare":1, "shareImage":1, "ExtendedLocation":"", "OriginQuery":"123.123.192.255", "tplt":"ip", "resourceid":"6006", "fetchkey":"123.123.192.255", "appinfo":"", "role_id":0, "disp_type":0}]});
看到返回的信息,就應該發現一些有用的東西了吧。所以我們可以通過模擬向百度的服務器發送請求來獲取我們想要的所在地信息
事實在之后的嘗試中我發現url后的參數列表中有一部分完全用不到,於是我就刪減了部分不影響結果的參數
以java語言實現
獲取返回信息的方法
/** * 通過用戶ip獲取用戶所在地 * @param userIp * @return */ public String getUserLocation(String userIp) { String url = "http://opendata.baidu.com/api.php?query=" + userIp; url += "&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=gbk&format=json"; return HttpRequest.sendGet(url); }
HttpReqeuest的Get方法(使用urlConnection) 向指定的url發送get請求
public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的連接 connection.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍歷所有的響應頭字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; }
在執行getUserLocation后返回的就是百度返回的json字符串了,所以也可以用一些json解析的方法來獲取json中的location信息,解析的方式各有不同,不再做過多描述了。
最后需要注意的一點,這個方法本身是基於baidu提供的ip地址獲取服務接口實現的,所有當百度的服務接口如果有所修改的話,這個功能是由失效的可能性的。
