package org.yeshi.utils;
|
|
import java.io.IOException;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import org.apache.commons.httpclient.HttpClient;
|
import org.apache.commons.httpclient.HttpException;
|
import org.apache.commons.httpclient.methods.GetMethod;
|
|
import net.sf.json.JSONObject;
|
|
public class IPUtil {
|
public static String getRemotIP(HttpServletRequest request) {
|
String ip = request.getHeader("x-forwarded-for");
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("Proxy-Client-IP");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("WL-Proxy-Client-IP");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_CLIENT_IP");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getRemoteAddr();
|
}
|
return ip;
|
}
|
|
public static Map<String, String> getIPInfo(String ip) {
|
Map<String, String> map = new HashMap<String, String>();
|
HttpClient client = new HttpClient();
|
GetMethod method = new GetMethod("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
|
try {
|
client.executeMethod(method);
|
String result = method.getResponseBodyAsString();
|
JSONObject object = JSONObject.fromObject(result);
|
if (object.optInt("code") == 0) {
|
map.put("city", object.optJSONObject("data").optString("city"));
|
map.put("country", object.optJSONObject("data").optString("country"));
|
return map;
|
}
|
|
} catch (HttpException e) {
|
e.printStackTrace();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
return map;
|
}
|
|
public static String getIPContry(String ip) {
|
HttpClient client = new HttpClient();
|
GetMethod method = new GetMethod("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
|
try {
|
client.executeMethod(method);
|
String result = method.getResponseBodyAsString();
|
JSONObject object = JSONObject.fromObject(result);
|
if (object.optInt("code") == 0) {
|
return object.optJSONObject("data").optString("country");
|
}
|
|
} catch (HttpException e) {
|
e.printStackTrace();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
return "";
|
}
|
|
}
|