1. 程式人生 > >伺服器獲取登入點的ip地址和城市名稱

伺服器獲取登入點的ip地址和城市名稱

package njg.ssh.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import njg.ssh.pojo.Ipaddr;

import org.apache.struts2.ServletActionContext;
import org.json.JSONException;
import org.json.JSONObject;
public class GetIp {
	private Ipaddr ipaddr;
	private HttpServletRequest request;
	public Ipaddr getIpaddr() {
		request=ServletActionContext.getRequest();
		ipaddr = new Ipaddr(getIpAddr(request),getCity(getIpAddr(request)),new GetTime().getTime());
		return ipaddr;
	}

	public void setIpaddr(Ipaddr ipaddr) {
		this.ipaddr = ipaddr;
	}

	protected String getIpAddr(HttpServletRequest request) {//獲取當前使用者登入ip地址
    	String ip="";
    	ip = request.getHeader("X-Forwarded-For");
		if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) {
			int index = ip.indexOf(',');
			if (index != -1) {return ip.substring(0, index);}
			else {return ip;}
		}
    	ip = request.getHeader("X-Real-IP");
		if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) {return ip;}
		ip = request.getRemoteAddr();
		if(ip.startsWith("0:")) return "127.0.0.1";
		else return ip;
	}
	protected String getCity(String ip) {//根據ip地址查詢IP所在城市
		try {
<span style="white-space:pre">			</span>//此url目的是用來獲取在百度地圖上查詢到的城市,其中AK是必填項,ak的值是在百度地圖API官網站點獲取,ip的值是登入IP地址。
			JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=fhz8tj5arBAsz6VWfyH8oe7xNdQc2DoM&ip=119.29.84.20");
//			System.out.println(json.toString());
//		    System.out.println(((JSONObject) json.get("content")).get("address"));
			return ((JSONObject) json.get("content")).get("address").toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	 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 = new JSONObject(jsonText);
		      return json;
		    } finally {
		      is.close();
		    }
		  }
}