package item_day2;
//1、使用淘宝解析ip地址
// 示例:用浏览器访问下面这段url,会显示出地址信息。只要我们将想要查询信息的IP地址
// 改变就会在页面显示出来
// http://ip.taobao.com/service/getIpInfo.php?ip=102.113.115.114
//
// 编写一个工具类IpParseUtil,
// 在IpParseUtil编写内部类RegionInfo
// 地域信息要封装在一个RegionInfo类里面,有三个属性,country、province、city
// IpParseUtil中包含一个方法名为ipParse(String ip)的方法,该方法可以
// 通过发送http请求到淘宝ip地址库,获取地域信息,返回值为RegionInfo的一个对象。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test1 {
public static void main(String[] args) throws IOException {
IpParseUtil util=new IpParseUtil();
System.out.println(util.ipParse("119.75.217.109").toString());
}
}
class IpParseUtil
{
public static class RegionInfo{
String country;
String province;
String city;
RegionInfo(String country,String province,String city)
{
this.city=city;
this.province=province;
this.country=country;
}
@Override
public String toString() {
return country+" "+province+" "+city;
}
}
RegionInfo ipParse(String ip) throws IOException {
String http="http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
//读取目的网页URL地址,获取网页源码
URL url=new URL(http);
HttpURLConnection httpUrl=(HttpURLConnection)url.openConnection();
InputStream is = httpUrl.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
String content="";
String str;
while((str=br.readLine())!=null)
{
content=content+str;
}
String[] strs=content.split(",");
String province=strs[4].split(":")[1].replaceAll("\"","");//.substring(10);
String city=strs[5].split(":")[1].replaceAll("\"","");
String country=strs[2].split(":")[1].replaceAll("\"","");
return new RegionInfo(country,province,city);
}
}
依赖:
<!-- https://mvnrepository.com/artifact/cz.mallat.uasparser/uasparser --> <dependency> <groupId>cz.mallat.uasparser</groupId> <artifactId>uasparser</artifactId> <version>0.6.1</version> </dependency>