e8c3e370e58561c8592594b7b53cf41ef929b63b.svn-base 2.5 KB
package yxy.timer.tool;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.alibaba.fastjson.JSONObject;

/***
 * 获取IP与地区
 */
public class getArea {
	public static void main(String[] args) {
		System.out.println(getArea("185.40.172.16"));
	}
	
	/**
	 * 通过IP查询所在地区
	 */
	public static String getArea(String ip){
		String IPArea="未知";
		
		HttpURLConnection httpUrlConnection = null;
		ByteArrayOutputStream baos = null;
		InputStream in = null;
		
		String path = ConfigPath.getCentreUrl();
		
		try {
			String url = path + "/webservice/ip?ip=" + ip; 
			URLConnection urlConnection = new URL(url).openConnection();
			httpUrlConnection = (HttpURLConnection) urlConnection;
			// 设置是否向httpUrlConnection输出,post请求,参数要放在http正文内,因此需要设为true,
			// 默认情况下是false;
			httpUrlConnection.setDoOutput(true);
			// 设置是否从httpUrlConnection读入,默认情况下是true;
			httpUrlConnection.setDoInput(true);
			// 忽略缓存
			httpUrlConnection.setUseCaches(false);
			// 设定请求的方法为"POST",默认是GET
			httpUrlConnection.setRequestMethod("POST");
			
			// 获得响应状态
			int responseCode = httpUrlConnection.getResponseCode();
			
			String result = null;
			
			if (HttpURLConnection.HTTP_OK == responseCode) {
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
					baos.flush();
				}

				result = baos.toString("UTF-8");  
			}
			if (result != null) {
				JSONObject data = JSONObject.parseObject(result);
				if (data.getInteger("code") == 200) {
					data = JSONObject.parseObject(data.getString("result"));
					IPArea = data.getString("country")+data.getString("prov")+data.getString("city");//获取某ip所在城市
				}
			}
			
		}catch (Exception e) {
			//System.out.println("获取地区失败!");
		} finally {
			if (baos != null) {
				try {
					baos.close(); 
				} catch (IOException e) {
					//System.out.println("获取地区失败!");
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					//System.out.println("获取地区失败!");
				}
			}
			
			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
			}
		}
		
        return IPArea;
	}
}