淘宝IP地址查询提供了API可以调用,返回的是JSON格式的数据流
1. 请求接口(GET):
http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]
2. 响应信息:
(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商
3. 返回数据格式:
{"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
"country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
"county_id":"-1","isp_id":"100017"}}
其中code的值的含义为,0:成功,1:失败。
Gson是google提供的用来解析json数据格式的库。解析淘宝返回的IP要用到JsonReader包
/**
* 通过IP获取地址
*
* @param ip
* @return
*/
public static String getIpInfo(String ip) {
String info = "";
try {
URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
htpcon.setRequestMethod("GET");
htpcon.setDoOutput(true);
htpcon.setDoInput(true);
htpcon.setUseCaches(false);
InputStream in = htpcon.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("code")) {
if(reader.nextInt()==1)
{
return info;
}
}
else if (name.equals("data")) {
return readData(reader);
} else {
reader.skipValue();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return info;
}
//读取IP数据
public static String readData(JsonReader reader) throws IOException {
String info = "";
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("country")) {
info += reader.nextString()+" ";
} else if (name.equals("region")) {
info += reader.nextString()+" ";
} else if (name.equals("city")) {
info += reader.nextString()+" ";
} else if (name.equals("isp")) {
info += reader.nextString()+" ";
}
else {
reader.skipValue();
}
}
reader.endObject();
return info;
}