Java phone,ip,idcard 获取地址信息

本文介绍通过编程方式获取手机号和IP地址的归属地信息,包括解析手机号运营商及所在城市,以及通过IP地址获取地理位置的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好记忆不如烂笔头,还是记下点什么好。

获取手机地址


直接贴代码查看

手机号归属地

    /**

     * 归属地查询

     * @param mobile

     * @return mobileAddress

     */

    @SuppressWarnings("unused")

    private static String getLocationByMobile(final Stringmobile)throws ParserConfigurationException, SAXException, IOException{ 

        String MOBILEURL =" http://www.youdao.com/smartresult-xml/search.s?type=mobile&q="

        String result = callUrlByGet(MOBILEURL +mobile,"GBK");

        StringReader stringReader = new StringReader(result); 

        InputSource inputSource = new InputSource(stringReader); 

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 

        Document document =documentBuilder.parse(inputSource);

 

        if (!(document.getElementsByTagName("location").item(0) ==null)) {

            return document.getElementsByTagName("location").item(0).getFirstChild().getNodeValue();

        }else{

            return "无此号记录!";

        }

    }

    

    /**

     * 获取URL返回的字符串

     * @param callurl

     * @param charset

     * @return

     */

    private static String callUrlByGet(Stringcallurl,Stringcharset){   

        String result = "";   

        try {   

            URL url = new URL(callurl);   

            URLConnection connection = url.openConnection();   

            connection.connect();   

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),charset));   

            String line;   

            while((line =reader.readLine())!=null){    

                result += line;   

                result += "\n";

            }

        } catch (Exception e) {   

            e.printStackTrace();   

            return "";

        }

        return result;

    }

    

    /**

     * 手机号码归属地

     * @param tel  手机号码

     * @return 135XXXXXXXX,联通/移动/电信,湖北武汉

     * @throws Exception

     * @author 

     */

    public static String getMobileLocation(Stringtel)throws Exception{

        Pattern pattern = Pattern.compile("1\\d{10}");

        Matcher matcher = pattern.matcher(tel);

        if(matcher.matches()){

            String url ="http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=" +tel;

            String result = callUrlByGet(url,"GBK");

            StringReader stringReader = new StringReader(result); 

            InputSource inputSource = new InputSource(stringReader); 

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 

            DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder(); 

            Document document =documentBuilder.parse(inputSource);

            String retmsg = document.getElementsByTagName("retmsg").item(0).getFirstChild().getNodeValue();

            if(retmsg.equals("OK")){

                String supplier = document.getElementsByTagName("supplier").item(0).getFirstChild().getNodeValue().trim();

                String province = document.getElementsByTagName("province").item(0).getFirstChild().getNodeValue().trim();

                String city = document.getElementsByTagName("city").item(0).getFirstChild().getNodeValue().trim();

                if (province.equals("-") ||city.equals("-")) {

                    return (getLocationByMobile(tel) +"," +supplier);

                }else {

                    return (province +"—" +city + "—" +supplier );

                }


            }else {

                return "无此号记录!";

            }

        }else{

            return tel+":手机号码格式错误!";

        }

    }

    

    

    public static void main(String[] args) {

        try {

            System.out.println(MobileLocationUtil.getMobileLocation("134xxxxxx78"));

        } catch (Exception e) {

            e.printStackTrace();

        }

    }



获取ip地址

贴代码看:


/**

*

* @param content

*            请求的参数 格式为:name=xxx&pwd=xxx

* @param encoding

*            服务器端请求编码。如GBK,UTF-8等

* @return

* @throws UnsupportedEncodingException

*/

public String getAddresses(Stringcontent, StringencodingString) throws UnsupportedEncodingException {

// 这里调用pconline的接口

String urlStr ="http://ip.taobao.com/service/getIpInfo.php";

// 从http://whois.pconline.com.cn取得IP所在的省市区信息

String returnStr =this.getResult(urlStr,content,encodingString);

if (returnStr !=null) {

// 处理返回的省市区信息

System.out.println(returnStr);

String[] temp =returnStr.split(",");

if (temp.length < 3) {

return"0";// 无效IP,局域网测试

}

String region = (temp[5].split(":"))[1].replaceAll("\"","");

region = decodeUnicode(region);// 省份


String country ="";

String area ="";

// String region = "";

String city ="";

String county ="";

String isp ="";

for (inti = 0;i < temp.length;i++) {

switch (i) {

case 1:

country = (temp[i].split(":"))[2].replaceAll("\"","");

country = decodeUnicode(country);// 国家

break;

case 3:

area = (temp[i].split(":"))[1].replaceAll("\"","");

area = decodeUnicode(area);// 地区

break;

case 5:

region = (temp[i].split(":"))[1].replaceAll("\"","");

region = decodeUnicode(region);// 省份

break;

case 7:

city = (temp[i].split(":"))[1].replaceAll("\"","");

city = decodeUnicode(city);// 市区

break;

case 9:

county = (temp[i].split(":"))[1].replaceAll("\"","");

county = decodeUnicode(county);// 地区

break;

case 11:

isp = (temp[i].split(":"))[1].replaceAll("\"","");

isp = decodeUnicode(isp);// ISP公司

break;

}

}


System.out.println(country +"=" +area + "=" +region +"=" + city +"=" +county + "=" +isp);

returnregion;

}

returnnull;

}


/**

* @param urlStr

*            请求的地址

* @param content

*            请求的参数 格式为:name=xxx&pwd=xxx

* @param encoding

*            服务器端请求编码。如GBK,UTF-8等

* @return

*/

private String getResult(StringurlStr, Stringcontent, String encoding) {

URL url = null;

HttpURLConnection connection =null;

try {

url =new URL(urlStr);

connection = (HttpURLConnection)url.openConnection();// 新建连接实例

connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒

connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒

connection.setDoOutput(true);// 是否打开输出流 true|false

connection.setDoInput(true);// 是否打开输入流true|false

connection.setRequestMethod("POST");// 提交方法POST|GET

connection.setUseCaches(false);// 是否缓存true|false

connection.connect();// 打开连接端口

DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据

out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx

out.flush();// 刷新

out.close();// 关闭输出流

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),encoding));// 往对端写完数据对端服务器返回数据

// ,以BufferedReader流来读取

StringBuffer buffer = new StringBuffer();

String line ="";

while ((line =reader.readLine()) !=null) {

buffer.append(line);

}

reader.close();

returnbuffer.toString();

}

catch (IOExceptione) {

e.printStackTrace();

}

finally {

if (connection !=null) {

connection.disconnect();// 关闭连接

}

}

returnnull;

}


/**

* unicode 转换成 中文

*

* @param theString

* @return

*/

public static String decodeUnicode(StringtheString) {

charaChar;

int len = theString.length();

StringBuffer outBuffer =new StringBuffer(len);

for (intx = 0;x < len;) {

aChar =theString.charAt(x++);

if (aChar =='\\') {

aChar =theString.charAt(x++);

if (aChar =='u') {

intvalue = 0;

for (inti = 0;i < 4; i++) {

aChar =theString.charAt(x++);

switch (aChar) {

case'0':

case'1':

case'2':

case'3':

case'4':

case'5':

case'6':

case'7':

case'8':

case'9':

value = (value << 4) +aChar -'0';

break;

case'a':

case'b':

case'c':

case'd':

case'e':

case'f':

value = (value << 4) + 10 +aChar -'a';

break;

case'A':

case'B':

case'C':

case'D':

case'E':

case'F':

value = (value << 4) + 10 +aChar -'A';

break;

default:

thrownew IllegalArgumentException("Malformed      encoding.");

}

}

outBuffer.append((char)value);

}

else {

if (aChar =='t') {

aChar ='\t';

}

elseif (aChar =='r') {

aChar ='\r';

}

elseif (aChar =='n') {

aChar ='\n';

}

elseif (aChar =='f') {

aChar ='\f';

}

outBuffer.append(aChar);

}

}

else {

outBuffer.append(aChar);

}

}

return outBuffer.toString();

}


// 测试

public staticvoid main(String[]args) {

IPAddressUtil addressUtils =new IPAddressUtil();

String ip ="125.70.11.136";

String address = "";

try {

address =addressUtils.getAddresses("ip=" +ip,"utf-8");

}

catch (UnsupportedEncodingExceptione) {

e.printStackTrace();

}

System.out.println(address);

}


身份证归属地

String uri ="http://qq.ip138.com/idsearch/index.asp?action=idcard&userid=" +idcard;

URL url = new URL(uri);

URLConnection urlConnection =url.openConnection();

BufferedReader br =new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"GBK"));

String str = "";

StringBuffer contents =new StringBuffer();

while ((str =br.readLine()) != null) {

contents.append(str);

}

br.close();

String regx1 ="<td class=\"tdc2\">(.*?)</td>";

Pattern p = Pattern.compile(regx1);

String text = contents.toString();

Matcher macher = p.matcher(text);

String result = "";

while (macher.find()) {

result =macher.group(1).trim().toString();

}

result = result.replaceAll("<br/>", "").replaceAll(" ","-");

System.out.println(result);


这些都是比较常用的方法。

但是都是依赖第三方的处理才可以使用的。

不是特别的好。

最好的是调用公安信息网的信息是最安全可靠的。

可以通过身份证号获取到以下信息: 1. 身份证号码的长度和格式是否正确 2. 身份证号码所属地区、出生日期、性别等基本信息 以下是一个Java代码示例,可以通过输入身份证号获取到以上信息: ```java import java.util.Calendar; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IDCardUtil { // 身份证号码正则表达式 private static final String ID_CARD_REGEX = "^\\d{17}[\\d|x|X]$"; // 省份代码 private static final String[] PROVINCE_CODE = {"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82"}; // 省份名称 private static final String[] PROVINCE_NAME = {"北京市", "天津市", "河北省", "山西省", "内蒙古自治区", "辽宁省", "吉林省", "黑龙江省", "上海市", "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省", "河南省", "湖北省", "湖南省", "广东省", "广西壮族自治区", "海南省", "重庆市", "四川省", "贵州省", "云南省", "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏回族自治区", "新疆维吾尔自治区", "台湾省", "香港特别行政区", "澳门特别行政区"}; /** * 根据身份证号获取出生日期 * * @param idCard 身份证号 * @return 出生日期,格式为 yyyy-MM-dd */ public static String getBirthDate(String idCard) { String birthDate = ""; if (idCard.length() == 18) { birthDate = idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14); } return birthDate; } /** * 根据身份证号获取性别 * * @param idCard 身份证号 * @return 性别,1表示男性,2表示女性 */ public static int getGender(String idCard) { int gender = 0; if (idCard.length() == 18) { gender = Integer.parseInt(idCard.substring(16, 17)); if (gender % 2 == 0) { gender = 2; } else { gender = 1; } } return gender; } /** * 根据身份证号获取所属地区 * * @param idCard 身份证号 * @return 所属地区 */ public static String getProvince(String idCard) { String province = ""; if (idCard.length() == 18) { String provinceCode = idCard.substring(0, 2); for (int i = 0; i < PROVINCE_CODE.length; i++) { if (provinceCode.equals(PROVINCE_CODE[i])) { province = PROVINCE_NAME[i]; break; } } } return province; } /** * 验证身份证号是否合法 * * @param idCard 身份证号 * @return true表示合法,false表示不合法 */ public static boolean isValid(String idCard) { boolean isValid = false; if (idCard != null && !"".equals(idCard.trim())) { Pattern pattern = Pattern.compile(ID_CARD_REGEX); Matcher matcher = pattern.matcher(idCard); if (matcher.matches()) { // 验证校验位 int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; String[] checkCode = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"}; int sum = 0; for (int i = 0; i < weight.length; i++) { sum += Integer.parseInt(idCard.substring(i, i + 1)) * weight[i]; } int mod = sum % 11; String lastChar = idCard.substring(17); if (lastChar.equalsIgnoreCase(checkCode[mod])) { isValid = true; } } } return isValid; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值