1. 需求其实很简单,就是开发一个可以获取IP地址的工具,实现方式1就是利用一些现有的接口进行获取,这种方式就是简单快捷,比如可以使用淘宝的接口:http://ip.taobao.com/service/getIpInfo.php?ip=, 后面跟上你的IP地址就行
实现的java的代码如下,基本上传入你的IP地址就可以了。
/**
* 发送http请求
* @param url
* @param content
* @return
*/
public static Map request(String url, String content) {
Map result = new HashMap();
String errorStr = "";
String status = "";
String response = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
// 设置请求属性
httpUrlConnection.setRequestProperty("Content-Type", "application/json");
httpUrlConnection.setRequestProperty("x-adviewrtb-version", "2.1");
// 发送POST请求必须设置如下两行
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(httpUrlConnection.getOutputStream());
// 发送请求参数
out.write(content);
// flush输出流的缓冲
out.flush();
httpUrlConnection.connect();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
response += line;
}
status = new Integer(httpUrlConnection.getResponseCode()).toString();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
errorStr = e.getMessage();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) { out.close();}
if (in != null) {in.close();}
} catch (Exception ex) {
ex.printStackTrace();
}
}
result.put("errorStr", errorStr);
result.put("response", response);
result.put("status", status);
return result;
}
/**
* 通过接口获取IP地址
* @param ip
* @return
*/
public static String getLocationByIP(String ip){
String taobao_server = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
Map objectMap = request(taobao_server, "");
// 转换为json对象
String status = objectMap.get("status").toString();
if (status.equals("200")) {
Object data = objectMap.get("response");
JSONObject jsonObject = JSONObject.fromObject(JSONObject.fromObject(data).getString("data"));
String country = jsonObject.get("country").toString();
String region = jsonObject.get("region").toString();
String city = jsonObject.get("city").toString();
String isp = jsonObject.get("isp").toString();
String address = country + region+ city + isp;
return address;
} else {
return "未知地址";
}
}
2.第二种方法,http://update.cz88.net/soft/setup.zip,到这个网站去下载一个IP地址库,然后到处为一个txt文件,最后通过Navicat等工具直接把数据导入到数据库,最后通过数据查询到 方式来获取IP,这种方式相对来说要更加高效了,基本上也不用受网络因素的影响。所以推荐大家使用第二种,当然如果只是进行测试使用,使用第一种也是更方便些。
评论
填写昵称与邮箱即可评论,无需登录。