public class AreaUtils {
@Autowired
private AreaService areaService;
public List<Area> IpDingWei(HttpServletRequest request) throws IOException {
//运用淘宝Ip定位,region_id StringUtils.getRemoteAddr(request) 123.232.172.54
String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + "123.232.172.54";
JSONObject json = readJsonFromUrl(url);
String city_id = (String) json.getJSONObject("data").get("city_id");
Area a = new Area();
a.setCode(city_id);
List<Area> area = areaService.findList(a);
return area;
}
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();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.fromObject(jsonText);
return json;
} finally {
is.close();
// System.out.println("同时 从这里也能看出 即便return了,仍然会执行finally的!");
}
}
}