第一步,要先获取到客户端的ip地址(百度一大堆,在这就不多说了了,想了解的可以自行百度):
这里需要注意的是本地开启apache服务的时候,当你调用这个方法的时候(包括访问jsp或者是html进行异步请求),获取到的ip还是内网的ip,并不是真实ip。不过没关系,当项目上生产、放服务器上的时候是可以获取到真实的ip的。
public static String getIp(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
第二步,ip到手了,找个第三方的接口吧,百度,高德的都可以,高德返回的json比较好解析。
在这之前要创建链接
/** * 读取 * @param rd * @return * @throws IOException */
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();
}
/** * 创建链接 * @param url * @return * @throws IOException * @throws JSONException */
private 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();
}
}
/** * 百度获取城市信息 * @param ip * @return * @throws JSONException * @throws IOException */
public static String baiduGetCityCode() throws JSONException, IOException{
String ip="";
//百度ak,自己去申请就可以
String ak="";
//这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ip="+ip+"&ak="+ak+"&coor=bd09ll");
Object obj = ((JSONObject) json.get("content")).get("address_detail");
String s=obj.toString();
JSONObject j = new JSONObject(s);
int city_code=(int) j.get("city_code");
String code=String.valueOf(city_code);
return code;
}
/** * 高德获取城市信息 * @return * @throws JSONException * @throws IOException */
public static String guideGetCityCode() throws JSONException, IOException{
String ip="";
//高德key
String key="";
JSONObject json = readJsonFromUrl("http://restapi.amap.com/v3/ip?ip="+ip+"&key="+key+"");
//String province = (String) json.get("province");
// String city = (String) json.get("city");
String adcode = (String) json.get("adcode");
return adcode;
}