欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 实时获取手机号码或电话号码的归属地

程序员文章站 2022-05-19 10:24:21
...

根据手机号码以及电话号码实时获取手机号码或电话号码的归属地。
手机号码归属地查询提供百度归属地查询、ip138查询(提供邮编和电话区号信息)、淘宝归属地查询(地区精确到省)。
电话号码归属地查询提供ip138查询。

添加jsoup依赖
  <dependency>
            <!-- jsoup HTML parser library @ http://jsoup.org/ -->
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
   </dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import net.dgg.tmd.foundation.platform.common.service.BaseService;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program:手机电话号码归属地查询
 * @description: 
 * @author: MMO_
 * @create: 2019-07-17 18:00
 */
public class GetPhoneAscription {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 验证url并且将请求后的参数返回(138网页抓取)
     *
     * @param phoneNumber 需要查询的手机号码
     * @return
     */
    public PhoneAscription checkUrl138TurnByJsoup(String phoneNumber) {
        PhoneAscription phoneAscription = null;
        try {
            String url = "http://www.ip138.com:8080/search.asp";
            Document doc = null;
            Connection connect = Jsoup.connect(url);
            connect.data("mobile", phoneNumber);
            connect.data("action", "mobile");
            doc = connect.timeout(2000).get();
            Elements els = doc.getElementsByClass("tdc2");
            if (null != els && els.size() > 2) {
                String info = els.get(1).text();
                if (StringUtils.isNotEmpty(info) && !" ".equals(info)) {
                    phoneAscription = new PhoneAscription();
                    String[] text = info.split(" ");
                    phoneAscription.setProvince(text[0]);
                    phoneAscription.setCity(text.length > 1 ? text[1] : text[0]);
                    phoneAscription.setCityCode(els.get(3).text());
                    phoneAscription.setServiceProvider(els.get(2).text());
                    phoneAscription.setPostCode(els.get(4).text().substring(0, 6));
                    phoneAscription.setMobile(phoneNumber.substring(0, 7));
                }
            }

        } catch (Exception e) {
            phoneAscription = null;
            logger.error("ip138号码查询归属地失败" + e);
        }
        return phoneAscription;
    }

    /**
     * 百度查询手机号码归属地
     *
     * @param phoneNumber
     * @return
     */
    public PhoneAscription checkPhoneNumberByBaiDu(String phoneNumber) {
        PhoneAscription phoneAscription = null;
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("tel", phoneNumber);
            Map<String, Object> responseArg = checkUrlTurnToMap("http://mobsec-dianhua.baidu.com/dianhua_api/open/location", params, "get");
            if (null != responseArg && responseArg.size() > 0) {
                Map map = (Map) responseArg.get("response");
                if (null != map && map.size() > 0) {
                    Map phoneMap = (Map) map.get(phoneNumber);
                    if (null != phoneMap && phoneMap.size() > 0) {
                        Map detailMap = (Map) phoneMap.get("detail");
                        if (null != detailMap && detailMap.size() > 0) {
                            phoneAscription = new PhoneAscription();
                            List<Map> areaMap = (List<Map>) detailMap.get("area");
                            if (null != areaMap && areaMap.size() > 0) {
                                phoneAscription.setCity(areaMap.get(0).get("city").toString());
                            }
                            phoneAscription.setProvince(detailMap.get("province").toString());
                            phoneAscription.setServiceProvider(detailMap.get("operator").toString());
                            phoneAscription.setMobile(phoneNumber.substring(0, 7));
                        }
                    }
                }
            }
        } catch (Exception e) {
            phoneAscription = null;
            logger.error("百度查询手机号码归属地失败:" + phoneNumber, e);
        }
        return phoneAscription;
    }


    /**
     * 百度查询手机号码归属地2
     *
     * @param phoneNumber
     * @return
     */
    public PhoneAscription checkPhoneNumberByBaiDuV2(String phoneNumber) {
        PhoneAscription phoneAscription = null;
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("resource_name", "guishudi");
            params.put("query", phoneNumber);
            Map<String, Object> responseArg = checkUrlTurnToMap("https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php", params, "get");
            if (null != responseArg && responseArg.size() > 0) {
                JSONArray jsonArray = (JSONArray) responseArg.get("data");
                List<Map> maps = JSONArray.parseArray(jsonArray.toJSONString(), Map.class);
                if (null != maps && maps.size() > 0) {
                    phoneAscription = new PhoneAscription();
                    phoneAscription.setCity(maps.get(0).get("city").toString());
                    phoneAscription.setProvince(StringUtils.isNotEmpty(maps.get(0).get("prov").toString()) ? maps.get(0).get("prov").toString() : maps.get(0).get("city").toString());
                    phoneAscription.setServiceProvider(maps.get(0).get("type").toString());
                    phoneAscription.setMobile(maps.get(0).get("key").toString());
                }
            }
        } catch (Exception e) {
            phoneAscription = null;
            logger.error("百度查询手机号码归属地2号码查询归属地失败:" + phoneNumber, e);
        }
        return phoneAscription;
    }


    /**
     * 验证url并且将请求后的参数返回(返回Map)
     *
     * @param url     请求地址
     * @param postArg 请求参数
     * @param postWay 请求方式 post get
     * @return
     */
    public Map<String, Object> checkUrlTurnToMap(String url, Map<String, Object> postArg, String postWay) {
        Map<String, Object> backResult = null;
        try {
            backResult = new HashMap<>();
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            // 设置超时
            requestFactory.setConnectTimeout(2000);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            String result = null;
            // get请求(默认post)
            if (StringUtils.isNotEmpty(postWay) && "get".equalsIgnoreCase(postWay)) {
                StringBuilder args = new StringBuilder("?");
                if (null != postWay && postWay.length() > 0) {
                    for (String key : postArg.keySet()) {
                        args.append(key + "=" + postArg.get(key) + "&");
                    }
                }
                String argsToString = args.substring(0, args.length() - 1);
                result = restTemplate.getForObject(url + argsToString, String.class);
            } else {
                result = restTemplate.postForObject(url, postArg, String.class);
            }
            if (StringUtils.isNotEmpty(result)) {
                backResult = json2Obj(result, Map.class);
                return backResult;
            } else {
                throw new NullPointerException("请求url返回失败");
            }
        } catch (Exception e) {
            backResult = null;
            logger.error("号码查询归属地失败" + e);
        }
        return backResult;
    }


    /**
     * 淘宝查询手机号码归属地(只精确到省)
     *
     * @param phoneNumber
     * @return
     */
    public PhoneAscription checkPhoneNumberByTaoBao(String phoneNumber) {
        PhoneAscription phoneAscription = null;
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("tel", phoneNumber);
            String result = checkUrlTurn("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm", params, "get");
            Map<String, Object> detailMap = new HashMap<>();
            detailMap = json2Obj(result.replace("__GetZoneResult_ = ", ""), Map.class);
            if (null != detailMap && detailMap.size() > 0) {
                phoneAscription = new PhoneAscription();
                phoneAscription.setProvince(detailMap.get("province").toString());
                phoneAscription.setCity(detailMap.get("province").toString());
                phoneAscription.setServiceProvider(detailMap.get("catName").toString());
                phoneAscription.setMobile(detailMap.get("mts").toString());
            }
        } catch (Exception e) {
            phoneAscription = null;
            logger.error("淘宝查询手机号码归属地号码查询归属地失败:" + phoneNumber, e);
        }
        return phoneAscription;
    }

    /**
     * 验证url并且将请求后的参数返回(返回String)
     *
     * @param url     请求地址
     * @param postArg 请求参数
     * @param postWay 请求方式 post get
     * @return
     */
    public String checkUrlTurn(String url, Map<String, Object> postArg, String postWay) {
        String result = null;
        try {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            // 设置超时
            requestFactory.setConnectTimeout(2000);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            // get请求(默认post)
            if (StringUtils.isNotEmpty(postWay) && "get".equalsIgnoreCase(postWay)) {
                StringBuilder args = new StringBuilder("?");
                if (null != postWay && postWay.length() > 0) {
                    for (String key : postArg.keySet()) {
                        args.append(key + "=" + postArg.get(key) + "&");
                    }
                }
                String argsToString = args.substring(0, args.length() - 1);
                result = restTemplate.getForObject(url + argsToString, String.class);
            } else {
                result = restTemplate.postForObject(url, postArg, String.class);
            }
        } catch (Exception e) {
            result = null;
            logger.error("号码查询归属地失败" + e);
        }
        return result;
    }


    /**
     * 电话号码归属地查询
     *
     * @param phoneNumber
     * @param operater
     * @return
     */
    public AreaPhoneCode telBelongArea(String phoneNumber) {
        String cityCode = null;
        String longCityCode = null;
        AreaPhoneCode areaPhoneCode = null;
        if (phoneNumber.contains("-")) {
            cityCode = phoneNumber.substring(0, phoneNumber.indexOf("-"));
        } else {
            cityCode = phoneNumber.substring(0, 3);
            longCityCode = phoneNumber.substring(0, 4);
        }
        areaPhoneCode = checkTELUrl138TurnByJsoup(StringUtils.isNotEmpty(longCityCode) ? longCityCode : cityCode);
        if (null == areaPhoneCode) {
            areaPhoneCode = checkTELUrl138TurnByJsoup(cityCode);
        }
        return areaPhoneCode;
    }


    /**
     * ip138根据电话区号查询地区(138网页抓取)
     *
     * @param phoneNumber 需要查询的电话号码
     * @return
     */
    public AreaPhoneCode checkTELUrl138TurnByJsoup(String phoneNumber) {
        AreaPhoneCode areaPhoneCode = null;
        try {
            // url
            String url = "http://www.ip138.com/post/search.asp";
            Document doc = null;
            Connection connect = Jsoup.connect(url);
            connect.data("zone", phoneNumber);
            connect.data("action", "zone2area");
            doc = connect.timeout(2000).get();
            Elements els = doc.getElementsByClass("tdc2");
            if (null != els && els.size() > 0) {
                String phoneInfo = els.get(1).text();
                if (StringUtils.isNotEmpty(phoneInfo)) {
                    areaPhoneCode = new AreaPhoneCode();
                    areaPhoneCode = dealIp138Info(phoneInfo, phoneNumber);
                }
            }
        } catch (Exception e) {
            areaPhoneCode = null;
            e.printStackTrace();
            logger.error("ip138电话号码查询归属地失败" + e);
        }
        return areaPhoneCode;
    }

    /**
     * ip138根据电话区号查询地区
     *
     * @param phoneInfo
     * @return
     */
    public AreaPhoneCode dealIp138Info(String phoneInfo, String areaNum) {
        AreaPhoneCode areaPhoneCode = null;
        String[] infos = phoneInfo.split(" ");
        if (null != infos && infos.length > 0) {
            areaPhoneCode = new AreaPhoneCode();
            areaPhoneCode.setProvince(infos[1]);
            String info = infos[2];
            areaPhoneCode.setCity(info.contains("邮编") ? infos[1] : info);
            areaPhoneCode.setCityCode(areaNum);
        }
        return areaPhoneCode;
    }

    /**
     * json字符串到对象
     *
     * @param jsonStr
     * @param objClass
     * @return
     */
    public static <T> T json2Obj(String jsonStr, Class<T> objClass) {
        T t = JSON.parseObject(jsonStr, objClass);
        return t;

    }
}

/**
 * 电话号码归属地查询
 */
class AreaPhoneCode {
    /**
     *
     */
    private Long id;

    /**
     * 城市名称
     */
    private String city;

    /**
     * 省
     */
    private String province;

    /**
     * 电话区号
     */
    private String cityCode;

    /**
     * @return id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return city
     */
    public String getCity() {
        return city;
    }

    /**
     * @param city
     */
    public void setCity(String city) {
        this.city = city == null ? null : city.trim();
    }

    /**
     * @return province
     */
    public String getProvince() {
        return province;
    }

    /**
     * @param province
     */
    public void setProvince(String province) {
        this.province = province == null ? null : province.trim();
    }

    /**
     * @return city_code
     */
    public String getCityCode() {
        return cityCode;
    }

    /**
     * @param cityCode
     */
    public void setCityCode(String cityCode) {
        this.cityCode = cityCode == null ? null : cityCode.trim();
    }
}

/**
 * 手机号码归属地查询
 */
class PhoneAscription {


    /**
     * 手机号码段
     */
    private String mobile;

    /**
     * 省份
     */
    private String province;

    /**
     * 市
     */
    private String city;

    /**
     * 运营商
     */
    private String serviceProvider;

    /**
     * 座机区号
     */
    private String cityCode;

    /**
     * 邮编
     */
    private String postCode;


    /**
     * 手机号码段
     *
     * @return mobile 手机号码段
     */
    public String getMobile() {
        return mobile;
    }

    /**
     * 手机号码段
     *
     * @param mobile 手机号码段
     */
    public void setMobile(String mobile) {
        this.mobile = mobile == null ? null : mobile.trim();
    }

    /**
     * 省份
     *
     * @return province 省份
     */
    public String getProvince() {
        return province;
    }

    /**
     * 省份
     *
     * @param province 省份
     */
    public void setProvince(String province) {
        this.province = province == null ? null : province.trim();
    }

    /**
     * 市
     *
     * @return city 市
     */
    public String getCity() {
        return city;
    }

    /**
     * 市
     *
     * @param city 市
     */
    public void setCity(String city) {
        this.city = city == null ? null : city.trim();
    }

    /**
     * 运营商
     *
     * @return service_provider 运营商
     */
    public String getServiceProvider() {
        return serviceProvider;
    }

    /**
     * 运营商
     *
     * @param serviceProvider 运营商
     */
    public void setServiceProvider(String serviceProvider) {
        this.serviceProvider = serviceProvider == null ? null : serviceProvider.trim();
    }

    /**
     * 座机区号
     *
     * @return city_code 座机区号
     */
    public String getCityCode() {
        return cityCode;
    }

    /**
     * 座机区号
     *
     * @param cityCode 座机区号
     */
    public void setCityCode(String cityCode) {
        this.cityCode = cityCode == null ? null : cityCode.trim();
    }

    /**
     * 邮编
     *
     * @return post_code 邮编
     */
    public String getPostCode() {
        return postCode;
    }

    /**
     * 邮编
     *
     * @param postCode 邮编
     */
    public void setPostCode(String postCode) {
        this.postCode = postCode == null ? null : postCode.trim();
    }


}
相关标签: 归属地 java