如何利用java程序查询大量手机号码的归属地

来源:互联网 发布:自学办公室软件 编辑:程序博客网 时间:2024/05/16 12:44
package zhang;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class GetMobile{

//本程序需要导入gson-2.1.jar
public static String getInputStream(String mobileNumber) throws Exception{
URL url = new URL("http://www.youdao.com/smartresult-xml/search.s?jsFlag=true&type=mobile&q="+mobileNumber);//调用有道//的API接口
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String resultString=reader.readLine();
reader.close();
return resultString;
}


public static void main(String[] args) throws Exception {//读取文件并把文件存入到list集合中
File file = new File("D://works//mobile.txt");
BufferedReader bw = new BufferedReader(new FileReader(file));
Map<String,List<String>> map =new HashMap<String,List<String>>();
List list = new ArrayList();
String line = null;
while((line= bw.readLine())!=null){
list.add(line);
}

bw.close();
List<String> tempList=null;  //利用map集合判断手机号码是否重复
for(int i = 0; i < list.size(); i++){
String s = (String) list.get(i);
String mobile = s.substring(0,7);
tempList=map.get(mobile);
if(tempList==null)
{
tempList=new ArrayList<String>();
tempList.add(s);
map.put(mobile, tempList);
}
else {
tempList.add(s);
}
}

Iterator iterator=map.entrySet().iterator();
GsonBuilder gsonBuilder=new GsonBuilder();//最后结果返回一个json,下面是用来解析处理json
  while (iterator.hasNext()) {
  java.util.Map.Entry<String, List<String>> entry = (java.util.Map.Entry<String, List<String>>) iterator.next();
  String  mobile = entry.getKey();
  String str = getInputStream(mobile);
  Gson gson=gsonBuilder.create();
  UpdateCall obj = gson.fromJson(str.substring(str.indexOf("{"), str.indexOf("}")+1), UpdateCall.class);
  String[] ad = obj.getLocation().split("\\s");
  System.out.println(ad[0]+"\t"+ad[1]+"\t"+mobile+"0000"+"\t" +mobile+"9999"+"\t"+"1");  
}
}
}
//上面是处理过程,下面要新建一个类用来支持上面的类


package zhang;


public class UpdateCall {
private String product;
private String phonenum;

private String location;


public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}

}


//本程序需要导入gson-2.1.jar

本程序最后生成的结果会分别查出号码的归属地,并存放到Map集合中。

结果可以根据本人需求修改

// 湖北 武汉 13971510000 13971519999 1  //最后输出的结果