java 根据IP地址获取对应的地域信息

/**根据IP地址获取地域信息
	 * @param ipAddress
	 * @return
	 */
	public static String getRegionInfo(String ipAddress) {
		String result = null;
		String url_str = "http://ip.taobao.com/service/getIpInfo.php?ip="
				+ ipAddress;
		try {
			URL url = new URL(url_str);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String inLine = in.readLine();
			in.close();
			if (("0").equals(getValueByJsonStr(inLine,p1))) {
				result = unicode2String(getValueByJsonStr(inLine,p2)+getValueByJsonStr(inLine,p3)+getValueByJsonStr(inLine,p4)+getValueByJsonStr(inLine,p5));
			} else {
				result = "获取不到该IP的地域信息";
			}
		} catch (Exception e) {
			result = "根据IP地址[" + ipAddress + "]获取地域信息的时候发生异常";
		}
		return result;
	}
	
	private static Pattern p1 = Pattern.compile("(?<=\"code\")(?:\\s*:\\s*)(?:\"?)(.*?)(?:\"?\\s*)(?:,)");
	private static Pattern p2 = Pattern.compile("(?<=\"country\")(?:\\s*:\\s*)(?:\"?)(.*?)(?:\"?\\s*)(?:,)");
	private static Pattern p3 = Pattern.compile("(?<=\"region\")(?:\\s*:\\s*)(?:\"?)(.*?)(?:\"?\\s*)(?:,)");
	private static Pattern p4 = Pattern.compile("(?<=\"city\")(?:\\s*:\\s*)(?:\"?)(.*?)(?:\"?\\s*)(?:,)");
	private static Pattern p5 = Pattern.compile("(?<=\"isp\")(?:\\s*:\\s*)(?:\"?)(.*?)(?:\"?\\s*)(?:,)");
	 
	 private static String getValueByJsonStr(String jsonStr,Pattern p){
	       Matcher m = p.matcher(jsonStr);
	       if(m.find()){
	    	 return m.group(1).toString();
	       }
	       return null;
	 }

	 
	/**
	 * unicode 转字符串
	 */
	public static String unicode2String(String unicode) {
		StringBuffer string = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		for (int i = 1; i < hex.length; i++) {
			// 转换出每一个代码点
			int data = Integer.parseInt(hex[i], 16);
			// 追加成string
			string.append((char) data);
		}
		return string.toString();
	}

猜你喜欢

转载自wangning1125.iteye.com/blog/2194989
今日推荐