接到一个需求,获取手机号码的归属地。这里记录一下,我们可以使用com.googlecode.libphonenumber的geocoder来获取手机号码归属地
<!--根据手机号查询归属地 -->
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.205</version>
</dependency>
public static final PhoneNumberOfflineGeocoder GEOCODER = PhoneNumberOfflineGeocoder.getInstance();
public static final int COUNTRY_CODE = 86;
/**
* 查询手机号码归属地
* @param phoneNum
* @return
*/
public static String getPhoneNumAttribution(String phoneNum) {
if (StringUtils.isNotBlank(phoneNum) && phoneNum.length() == 11) {
try {
long phone = Long.parseLong(phoneNum);
Phonenumber.PhoneNumber pn = new Phonenumber.PhoneNumber();
pn.setCountryCode(COUNTRY_CODE);
pn.setNationalNumber(phone);
return GEOCODER.getDescriptionForNumber(pn, Locale.CHINESE);
}catch (Exception e){
log.error("查询手机号码归属地失败,手机号:{},异常:{}",phoneNum,e);
return "未知";
}
}
log.info("查询手机号码归属地失败,手机号:{},异常:{}",phoneNum);
return "未知";
}