根据手机号获取号码归属地

关键代码:使用淘宝提供的接口,使用JsonPath解析JSON字符串

 public String getProvideByPhoneNum( String phoneNum){
        String province = null;
        try {
            String url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="+phoneNum;
            String s = HttpUtils.doGet(url.trim());
            s = s.replace("__GetZoneResult_ = ","");
            province = JsonPath.parse(s).read("$.province");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return province;
    }

http请求工具类,使用HttpClient工具类

public class HttpUtils {
    private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);

    public static String Curl(String PostUrl, String[] Parameters) throws Exception {
        if (null == PostUrl || null == Parameters || Parameters.length == 0) {
            return null;
        }
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            //建立URL之间的连接
            URLConnection conn = new URL(PostUrl).openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("Host", "data.zz.baidu.com");
            conn.setRequestProperty("User-Agent", "curl/7.12.1");
            conn.setRequestProperty("Content-Length", "83");
            conn.setRequestProperty("Content-Type", "text/plain");
            //发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //获取conn对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数
            String param = "";
            for (String s : Parameters) {
                param += s + "\n";
            }
            out.print(param.trim());
            //进行输出流的缓冲
            out.flush();
            //通过BufferedReader输入流来读取Url的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送post请求出现异常!" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 普通POST请求
     *
     * @param url
     * @param jsonFormString
     * @return
     * @throws Exception
     */

    public static JSONObject doPost(String url, String jsonFormString) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.addHeader("text/plain", "UTF-8");
        post.addHeader("Content-Type", "application/json");
        LOG.info("POST请求内容:{}", jsonFormString);

        StringEntity s = new StringEntity(jsonFormString, Charsets.UTF_8);
        post.setEntity(s);

        return executePost(post, client);
    }

    /**
     * 以form方式请求post
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static JSONObject doPostToForm(String url, Map<String, String> map) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.addHeader("text/plain", "UTF-8");
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");

        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            pairList.add(new BasicNameValuePair(key, map.get(key)));
        }
        post.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
        return executePost(post, client);
    }

    /**
     * GET方式请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        get.setHeader("Content-Type", "application/json; charset=UTF-8");
        String response = null;
        HttpResponse httpResponse = client.execute(get);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            response = EntityUtils.toString(httpResponse.getEntity());// 返回json格式:
        } else {
            String errorMsg = EntityUtils.toString(httpResponse.getEntity());
            throw new RuntimeException(errorMsg);
        }
        return response;
    }

    public static String HttpUrlGet(String url) throws IOException {
        URL u = new URL(url);
        HttpURLConnection con = (HttpURLConnection) u.openConnection();
        con.connect();
        String result = "";
        if (con.getResponseCode() == HttpStatus.SC_OK) {
            InputStream in = con.getInputStream();
            BufferedReader buff = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String line = null;
            while ((line = buff.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            buff.close();
        } else {
            result = "请求错误";
        }
        return result;
    }

    /**
     * 执行post请求
     *
     * @param post
     * @param client
     * @return
     * @throws IOException
     */
    private static JSONObject executePost(HttpPost post, HttpClient client) throws IOException {
        HttpResponse httpResponse = client.execute(post);
        JSONObject response = null;
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(httpResponse.getEntity());// 返回json格式:
            LOG.info("result的内容: {}", result);
            response = JSONObject.parseObject(result);
        } else {
            String errorMsg = EntityUtils.toString(httpResponse.getEntity());
            throw new RuntimeException(errorMsg);
        }
        return response;
    }

    /**
     * 带参数的get请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String doGetWhitParams(String url, List<NameValuePair> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        String urlEntity = "";
        try {
            //转换为键值对
            urlEntity = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
            //创建get请求
            HttpGet get = new HttpGet(url + "?" + urlEntity);
            //执行get请求
            response = httpClient.execute(get);
            //得到响应体
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //消耗实体内容
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭相应 丢弃http连接
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * post请求发送form-data
     *
     * @param url
     * @param filePath
     * @return
     */
    public static String doPostWhitFile(String url, String filePath) {
        String result = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            File file = new File(filePath);
            if (file == null || !file.exists()) {
                throw new FileNotFoundException();
            }
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody("media", file).setMode(HttpMultipartMode.RFC6532);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(multipartEntityBuilder.build());
            httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * post 发送json数据
     * @param url
     * @param strJson
     * @return
     */
    public static String doPostWhitJson(String url, String strJson) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-type", "application/json; charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setEntity(new StringEntity(strJson, Charset.forName("UTF-8")));
        try {
            response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

  

原文地址:https://www.cnblogs.com/wiseroll/p/8278755.html

时间: 2024-10-15 12:08:28

根据手机号获取号码归属地的相关文章

在java中如何根据手机号查询号码归属地

1.maven项目中配置 <dependency><groupId>com.googlecode.libphonenumber</groupId><artifactId>geocoder</artifactId><version>2.15</version></dependency> <dependency><groupId>com.googlecode.libphonenumber&l

手机安全卫士------查询号码归属地

效果图: 技术点: 数据库的查询操作 正则表达式 监听输入框的输入事件 思路: 查询号码归属地的方法有两种: 1.网络查询,通过网上的一些接口,可以查询到JSON数据等 2.本地查询,APK中,自带一个数据库,放置号段对应的地点信息 考虑到用户的使用场景,决定采用本地查询的方式来实现这个功能. 本功能采用的是 小米提供的数据库. 内部有两张表: data1: id:手机号码的前七位 outkey:外键 data2: id:对应表1中的外键 location:位置 area:区号 查询手机号码的思

[android] 手机卫士来电显示号码归属地

继续N天前的项目 开启服务监听手机来电,查询数据库,显示归属地 详细内容可以参考这篇博文:http://www.cnblogs.com/taoshihan/p/5331232.html AddressService.java package com.qingguow.mobilesafe.service; import com.qingguow.mobilesafe.utils.NumberQueryAddressUtil; import android.app.Service; import

android 如何关闭来电号码归属地

MTK平台号码归属地分为两种:1.手机号码归属地:2.固话号码归属地: 手机号码归属地: 是MTK自己做的,关闭只需要关闭MTK_PHONE_NUMBER_GEODESCRIPTION这个option即可: 数据库文件所在路径为 alps/mediatek/external/geocoding/geocoding.db: 仅支持汉语. 固话号码归属地: 是Google Android系统自带的,关闭需要注解掉Google的原始code: 数据库文件所在路径为 alps/external/libp

如何批量查询号码归属地,可以导入表格xlsx、txt直接查询

我发现这个程序写的还不错,批量批量查询号码归属地.公司做业务的时候需要. 程序可以从输入框导入手机号码,进行批量查询号码的归属地信息,详细信息有:省份.城市.运营商. 直接导入电子表格Excel文件查询,也可以导入txt.csv等文件. 程序在这里: 批量查询号码的归属地信息 省份.城市.运营商 程序界面: 查询速度很快,几乎是5秒内能5万数据. 说是一次能查几十万,程序做的挺好 查询结果是这样的 导出的Excel文件,根据不同的列,在表格也能非常方便筛选,可以按省份筛选.按城市筛选.按号码运营

Android 开发工具类 31_WebService 获取手机号码归属地

AndroidInteractWithWebService.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12=

Android JSON原生解析的几种思路,以号码归属地,笑话大全,天气预报为例演示

Android JSON原生解析的几种思路,以天气预报为例 今天项目中要实现一个天气的预览,加载的信息很多,字段也很多,所以理清了一下思路,准备独立出来写一个总结,这样对大家还是很有帮助的,老司机要开车了 涉及到网络,你就一定要先添加权限,准没错 <!--网络权限--> <uses-permission android:name="android.permission.INTERNET" /> 一.归属地查询(JSONObject) 这个也是最简单的一类Json

利用WebApi获取手机号码归属地

前述: 在WebApi中,涉及到一个重要的类,HttpWebRequest. 学习link:httpwebrequest详解 示例演示: 代码示例: 1.前端代码: 1 @{ 2 ViewBag.Title = "Index"; 3 Layout = null; 4 } 5 @*<script src="~/Views/js/jquery-1.7.1.js"></script>*@ 6 @*<script src="~/Vie

手机号获取验证码、验证验证码是否正确

}else { alert("验证码已发送,请注意查收"); time();//调用验证码倒计时 document.getElementById('iputCode').setAttribute('class',result);//让该元素添加calss} /*** 点击获取验证码后显示倒数时间*/var wait = 60;// 定义短信发送倒计时时间function time(){ ocument.getElementById('obtain').disabled = false;