import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ceshi {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("E:\\ip.txt"), "utf-8")); //
File file = new File("E:\\result.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
String country = "\"country\":\"(.*)\"";//匹配國家
String area = "\"area\":\"(.*)\"";//匹配省份
String city = "\"city\":\"(.*)\"";//匹配城市
String line = null;
String countryStr;
String areaStr;
String cityStr;
while ((line = br.readLine()) != null) {
if(!line.trim().equals("")){
line = get(line.trim());
countryStr = getValue(line, country);
areaStr = getValue(line, area);
cityStr = getValue(line, city);
bw.append(countryStr + " " + areaStr + " " + cityStr);
}
}
br.close();
bw.close();
System.out.println("end");
}
public static String convert(String utfString){
StringBuilder sb = new StringBuilder();
int i = -1;
int pos = 0;
while((i=utfString.indexOf("\\u", pos)) != -1){
sb.append(utfString.substring(pos, i));
if(i+5 < utfString.length()){
pos = i+6;
sb.append((char)Integer.parseInt(utfString.substring(i+2, i+6), 16));
}
}
return sb.toString();
}
public static String getValue(String line, String patternStr) throws UnsupportedEncodingException{
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(new String(line));
String value = "";
if(matcher.find()){
value = matcher.group(0);
value = value.split(":")[1];
value = value.split(",")[0];
value = value.substring(1, value.length()-1);
}
return value;
}
public static String get(String ip) throws IOException{
String urlNameString = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), Charset.forName("utf-8")));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
return convert(result);
}
}
調用IP接口
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.