java通过免费接口获取ip地址的服务商信息

时间:2022-07-10 20:17:28

今天分享一个免费在线的小工具的开发代码就是通过淘宝提供的接口获取服务商信息,
工具地址:http://www.yzcopen.com/seo/ipadress

代码如下:

public class YzcPattern {
/**
* ip地址接口
*/
private final static String ipurl ="http://ip.taobao.com/service/getIpInfo.php?ip="; /**
* 判断ip
* @param text
* @return
*/
public static boolean ipCheck(String text) {
if (text != null && !text.isEmpty()) {
// 定义正则表达式
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
// 判断ip地址是否与正则表达式匹配
if (text.matches(regex)) {
return true;
// 返回判断信息
//return text + "\n是一个合法的IP地址!";
} else {
return false;
// 返回判断信息
//return text + "\n不是一个合法的IP地址!";
}
}
return false;
} /**
* 读取IP的
* @param getAccessTokenUrl
* @return
*/
public static String getAuth(String getAccessTokenUrl) {
HttpURLConnection connection = null;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打开和URL之间的连接
connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestProperty("User-Agent", Const.UserAgent);
connection.setRequestMethod("GET");
connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
connection.setRequestProperty("Content-Type",
"application/json");
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
return result;
} catch (Exception e) {
e.printStackTrace();
}finally{
if(connection!=null){
connection.disconnect();
}
}
return null;
} public static void main(String[] args) throws Exception {
String ip="您的ip";
boolean bo = YzcPattern.ipCheck(ip);
if(bo){
String url = ipurl+ip;
String result = getAuth(url);
} //获得的结果 {"code":0,"data":{"ip":"58.87.124.194","country":"中国","area":"","region":"天津","city":"天津","county":"XX","isp":"电信","country_id":"CN","area_id":"","region_id":"120000","city_id":"120100","county_id":"xx","isp_id":"100017"}}
}
}