判断ip归属地

//judgeIP.java
//httpcomponents-client-4.3.6.jar
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class JudgeIP {
	class IPInfo{
		public String ip,country,city,isp;
		public String toString(){
			return ip+","+country+","+city+","+isp;
		}
	}

	public static void main(String[] args) throws ClientProtocolException,
			IOException {
		String ip = "61.152.150.146";
		String jsonStr = httpGet(ip);
		jsonStr=dealUnicode(jsonStr);
		IPInfo ipInfo=new JudgeIP().new IPInfo();
		ipInfo.ip=dealJson(jsonStr, "ip");
		ipInfo.country=dealJson(jsonStr, "country");
		ipInfo.city=dealJson(jsonStr, "city");
		ipInfo.isp=dealJson(jsonStr, "isp");
		
		System.out.println(ipInfo);

	}

	static String httpGet(String ip) throws ClientProtocolException,
			IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response1 = null;
		StringBuilder sb = new StringBuilder();
		try {
			HttpGet httpGet = new HttpGet(
					"http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
			response1 = httpclient.execute(httpGet);
			HttpEntity entity1 = response1.getEntity();
			InputStream instream = entity1.getContent();
			String s = null;

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					instream, "utf-8"));
			while ((s = reader.readLine()) != null) {
				sb.append(s + "\r\n");
			}
			EntityUtils.consume(entity1);
			return sb.toString();
		} finally {
			response1.close();
		}
	}

	static String dealUnicode(String str) {
		//此时str是:{"country":"\u4e2d\u56fd" 这样的形式,需要转换
		Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})");
		Matcher m = reUnicode.matcher(str);
		StringBuffer sb = new StringBuffer(str.length());
		while (m.find()) {
			m.appendReplacement(sb,
					Character.toString((char) Integer.parseInt(m.group(1), 16)));
		}
		m.appendTail(sb);
		return sb.toString();
	}
	static String dealJson(String jsonStr,String key){
		int index=jsonStr.indexOf(key);
		index+=key.length()+"\":\"".length();
		int indexEnd=jsonStr.indexOf("\"", index);
		return jsonStr.substring(index, indexEnd);
	}
}
/*61.152.150.146,中国,上海市,电信*/

你可能感兴趣的:(Java-EE)