java获取请求的ip地址,并解析ip所属地区
时间: 2023-08-18 20:07:55 浏览: 106
你可以通过Java中的HttpServletRequest对象来获取请求的IP地址。以下是获取IP地址的代码:
```java
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.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
```
然后你可以通过调用第三方的IP地址库来解析IP所属地区,比如淘宝IP地址库。以下是解析IP地址所属地区的代码:
```java
String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ipAddress;
String json = IOUtils.toString(new URL(url), Charset.forName("UTF-8"));
JSONObject obj = JSONObject.parseObject(json);
String province = obj.getJSONObject("data").getString("region");
String city = obj.getJSONObject("data").getString("city");
```
这里使用了阿里巴巴的Fastjson库来解析返回的JSON数据。
阅读全文