這期內容當中小編將會給大家帶來有關怎么在Java中使用Request請求獲取IP地址對應的省份,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
步驟:
1. 通過Request獲取IP
2. 通過IP獲取對應省份、城市
3. 通過設置的省份和IP對應省份進行比對,展示內容
通過Request獲取IP
可以參考我的另外一篇文章【Java 通過Request請求獲取IP地址】下面是代碼:
public class IpAdrressUtil {
/**
* 獲取Ip地址
* @param request
* @return
*/
private static String getIpAdrress(HttpServletRequest request) {
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
//多次反向代理后會有多個ip值,第一個ip才是真實ip
int index = XFor.indexOf(",");
if(index != -1){
return XFor.substring(0,index);
}else{
return XFor;
}
}
XFor = Xip;
if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
return XFor;
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
}通過IP獲取對應省份、城市
使用【GeoLite2 City】庫
目前開源的IP地址庫與城市對應關系用的比較多的是MaxMind公司的GeoLite數據庫,GeoLite數據庫有開源版本和收費版本,我們使用的是開源版本,GeoLite目前已經更新到2了,所以我們下載GeoLite2 City庫。
官方下載地址是【http://dev.maxmind.com/geoip/geoip2/geolite2/】
本地下載地址是【http://xiazai.jb51.net/201710/yuanma/GeoLite2-City_20171003(jb51.net).rar】

如果覺得慢就用迅雷下。下載完成后就是,下載完成就解壓。得到【GeoLite2-City.mmdb】文件,這個就是數據庫。

Java例子是這樣使用的:
首先在項目中加入maven支持
<dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version>2.8.1</version> </dependency>
然后通過GeoLite2查詢得到省份、城市:
public static void main(String[] args) throws Exception{
// 創建 GeoLite2 數據庫
File database = new File("/Users/admin/GeoLite2-City.mmdb");
// 讀取數據庫內容
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("171.108.233.157");
// 獲取查詢結果
CityResponse response = reader.city(ipAddress);
// 獲取國家信息
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'CN'
System.out.println(country.getName()); // 'China'
System.out.println(country.getNames().get("zh-CN")); // '中國'
// 獲取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Guangxi Zhuangzu Zizhiqu'
System.out.println(subdivision.getIsoCode()); // '45'
System.out.println(subdivision.getNames().get("zh-CN")); // '廣西壯族自治區'
// 獲取城市
City city = response.getCity();
System.out.println(city.getName()); // 'Nanning'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // 'null'
System.out.println(city.getNames().get("zh-CN")); // '南寧'
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 22.8167
System.out.println(location.getLongitude()); // 108.3167
}如果是生產環境,可以直接創建一個Service,在Service初始化的時候創建reader對象,然后在公共方法中通過ip查詢地址,下面以省份為例:
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.net.InetAddress;
/**
* IP地址服務
*/
@Service
public class IpAddressService {
private static Logger logger = LoggerFactory.getLogger(IpAddressService.class);
private static String dbPath = "/usr/local/GeoLite2-City.mmdb";
private static DatabaseReader reader;
@Autowired
private Environment env;
@PostConstruct
public void init() {
try {
String path = env.getProperty("geolite2.city.db.path");
if (StringUtils.isNotBlank(path)) {
dbPath = path;
}
File database = new File(dbPath);
reader = new DatabaseReader.Builder(database).build();
} catch (Exception e) {
logger.error("IP地址服務初始化異常:" + e.getMessage(), e);
}
}
public String getSubdivision(String ipAddress){
try {
CityResponse response = reader.city(InetAddress.getByName(ipAddress));
return response.getMostSpecificSubdivision().getNames().get("zh-CN");
}catch (Exception e){
logger.error("根據IP[{}]獲取省份失敗:{}", ipAddress, e.getMessage());
return null;
}
}
}然后在需要的地方就行判斷:
String areaNames = {"北京","天津","上海"};
String subdivision = ipAddressService.getSubdivision(getIpAdrress(request));
// 匹配
if(containsArea(subdivision, areaNames)){
// 處理...
}匹配方法:
private boolean containsArea(String name, String[] areaNames) {
if(StringUtils.isBlank(name)){
return false;
}
for(String areaName : areaNames){
if(name.contains(areaName)){
return true;
}
}
return false; // 按地域返回數據
}上述就是小編為大家分享的怎么在Java中使用Request請求獲取IP地址對應的省份了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。