获取手机号码归属地

通过google的libphonenumber解析,格式化,存储和校验国际电话号码。目前针对国内手机号做的验证。

导入maven依赖

 
            com.googlecode.libphonenumber
            libphonenumber
            8.7.1
        
        
            com.googlecode.libphonenumber
            geocoder
            2.76
        
        
            com.googlecode.libphonenumber
            carrier
            1.66
        

相关代码如下:

public class PhoneAddrUtil {
    private static PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    private static PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper.getInstance();
    private static PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();

    /**
     * 根据国家代码和手机号  判断手机号是否有效
     * @param phoneNumber
     * @param countryCode
     * @return
     */
    public static boolean checkPhoneNumber(String phoneNumber, String countryCode){

        int ccode = Integer.valueOf(countryCode);
        long phone = Long.valueOf(phoneNumber);

        Phonenumber.PhoneNumber pn = new Phonenumber.PhoneNumber();
        pn.setCountryCode(ccode);
        pn.setNationalNumber(phone);

        return phoneNumberUtil.isValidNumber(pn);

    }

    /**
     * 根据国家代码和手机号  判断手机运营商
     * @param phoneNumber
     * @param countryCode
     * @return
     */
    public static String getCarrier(String phoneNumber, String countryCode){

        int ccode = Integer.valueOf(countryCode);
        long phone = Long.valueOf(phoneNumber);

        Phonenumber.PhoneNumber pn = new Phonenumber.PhoneNumber();
        pn.setCountryCode(ccode);
        pn.setNationalNumber(phone);
        //返回结果只有英文,自己转成成中文
        String carrierEn = carrierMapper.getNameForNumber(pn, Locale.ENGLISH);
        String carrierZh = "";
        carrierZh += geocoder.getDescriptionForNumber(pn, Locale.CHINESE);
        switch (carrierEn) {
            case "China Mobile":
                carrierZh += " 移动";
                break;
            case "China Unicom":
                carrierZh += " 联通";
                break;
            case "China Telecom":
                carrierZh += " 电信";
                break;
            default:
                break;
        }
        return carrierZh;
    }

    /**
     * 无国家码 默认用中国
     * @param phoneNumber
     * @return
     */
    public  static String getCarrier(String phoneNumber) {
        return getCarrier(phoneNumber,"86");
    }

    public static void main(String[] args) {
        String address = PhoneAddrUtil.getCarrier("17600110011");
        System.out.println(address);
    }
}

输出结果如下:

获取手机号码归属地_第1张图片

 

你可能感兴趣的:(java,maven,intellij-idea)