title: 获取请求真实ip并找到中文地址 categories:
JAVA tags:java abbrlink: 652256356 date: 2019-10-26 10:17:34
原文地址
JAVA获取HttpServletRequest的真实ip
static String
getClientIpAddr(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_X_FORWARDED_FOR");
}
if (ip
== null
|| ip
.length() == 0 || "unknown".equalsIgnoreCase(ip
)) {
ip
= request
.getHeader("HTTP_X_FORWARDED");
}
if (ip
== null
|| ip
.length() == 0 || "unknown".equalsIgnoreCase(ip
)) {
ip
= request
.getHeader("HTTP_X_CLUSTER_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_FORWARDED_FOR");
}
if (ip
== null
|| ip
.length() == 0 || "unknown".equalsIgnoreCase(ip
)) {
ip
= request
.getHeader("HTTP_FORWARDED");
}
if (ip
== null
|| ip
.length() == 0 || "unknown".equalsIgnoreCase(ip
)) {
ip
= request
.getHeader("HTTP_VIA");
}
if (ip
== null
|| ip
.length() == 0 || "unknown".equalsIgnoreCase(ip
)) {
ip
= request
.getHeader("REMOTE_ADDR");
}
if (ip
== null
|| ip
.length() == 0 || "unknown".equalsIgnoreCase(ip
)) {
ip
= request
.getRemoteAddr();
}
return ip
;
}
获取请求中文详细地址
ip查询api
String url
= "http://ip-api.com/json/";
url
= url
+ip
+"?lang=zh-CN&fields=6025215";
HttpGet httpGet
=new HttpGet(url
);
String ipRealAddress
= null
;
try {
CloseableHttpResponse response
= httpClient
.execute(httpGet
);
HttpEntity httpEntity
=response
.getEntity();
ipRealAddress
= EntityUtils
.toString(httpEntity
);
} catch (IOException e
) {
e
.printStackTrace();
}