java使用淘宝API读写json实现手机归属地查询功能代码

2022-10-20,,,,

一般查询手机归属地内容应该很好用json格式保存,在网上找到了淘宝的归属地api,并下了处理json相关的jar包,做了这个手机归属地查询功能

复制代码 代码如下:
package com.think.java;

import java.io.bufferedreader;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.malformedurlexception;
import java.net.url;
import java.util.arraylist;
import java.util.list;
import net.sf.json.jsonarray;
import net.sf.json.jsonobject;

public class testmobilecity {   

    /**
     * 测试手机号码是来自哪个城市的,利用淘宝的api
     * @param mobilenumber 手机号码
     * @return
     * @throws malformedurlexception
     */
    public static string calcmobilecity(string mobilenumber) throws malformedurlexception{
        string jsonstring = null;
        jsonarray array = null;
        jsonobject jsonobject = null;
        string urlstring = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobilenumber;
        stringbuffer sb = new stringbuffer();
        bufferedreader buffer;
        url url = new url(urlstring);
        try{
            inputstream in = url.openstream();

            // 解决乱码问题
            buffer = new bufferedreader(new inputstreamreader(in,"gb2312"));
            string line = null;
            while((line = buffer.readline()) != null){
                sb.append(line);
            }
            in.close();
            buffer.close();
            // system.out.println(sb.tostring());
            jsonstring = sb.tostring();
            // 替换掉“__getzoneresult_ = ”,让它能转换为jsonarray对象
            jsonstring = jsonstring.replaceall("^[__]\\w{14}+[_ = ]+", "[");
            // system.out.println(jsonstring+"]");
            string jsonstring2 = jsonstring + "]";
            // 把string转化为json对象
            array = jsonarray.fromobject(jsonstring2);

            // 获取jsonarray的jsonobject对象,便于读取array里的键值对
            jsonobject = array.getjsonobject(0);       

        }catch(exception e){
            e.printstacktrace();
        }
        return jsonobject.getstring("province");
    }

    /**
     * 计算多个号码的归属地
     * @param mobilenumbers 号码列表
     * @return
     * @throws malformedurlexception
     */
    public static jsonobject calcmobilescities(list<string> mobilenumbers) throws malformedurlexception{
        jsonobject jsonnumbercity = new jsonobject();
        for(string mobilenumber : mobilenumbers){
            jsonnumbercity.put(mobilenumber, calcmobilecity(mobilenumber));            ;
        }       
        return jsonnumbercity;
    }

    public static void main(string[] args) throws exception{
        string testmobilenumber = "1881758452";
        system.out.println(calcmobilecity(testmobilenumber));
        list<string> mobilelist = new arraylist<string>();
        for(int i = 1350345; i < 1350388; i++){
            mobilelist.add(string.valueof(i));
        }
        system.out.println(calcmobilescities(mobilelist).tostring());
    }
}

《java使用淘宝API读写json实现手机归属地查询功能代码.doc》

下载本文的Word格式文档,以方便收藏与打印。