平常我们的项目需要将访客记录下来,所以我们需要知道访客的一些信息!
代码如下:
package com.yanghui.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 根据IP地址获取详细的地域信息
* @author YH
*/
public class AddressUtil {
/**
* 根据IP地址获取详细的地域信息
* @param content 请求的参数,例如格式为:ip=192.168.18.90
* @param encodingString 服务器端请求编码。如 GBK,UTF-8等
*/
public String getAddresses(String content, String encodingString)
throws UnsupportedEncodingException {
String urlStr = "http://ip.taobao.com/outGetIpInfo";
String returnStr = this.getResult(urlStr, content, encodingString);
if (returnStr != null) {
// 处理返回的省市区信息
String[] temp = returnStr.split(",");
/** 国家 */
String country = (temp[1].split(":"))[1].replaceAll("\"", "");
/** 省份 */
String province = (temp[11]).split(":")[1].replaceAll("\"", "");
/** 城市 */
String city = (temp[4]).split(":")[1].replaceAll("\"", "");
/** 运营商 */
String isp = (temp[6]).split(":")[1].replaceAll("\"", "");
if ("内网IP".equals(isp)) {
return "内网IP:未知城市";
}
return country + province + "省" + city + "市";
}
return "未知城市";
}
/**
* @param urlStr 请求的接口地址
* @param content 请求的参数,例如格式为:ip=192.168.18.90
* @param encoding 服务器端请求编码。如GBK,UTF-8等
* @return
*/
private String getResult(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
// 新建连接实例
connection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间,单位毫秒
connection.setConnectTimeout(2000);
// 设置读取数据超时时间,单位毫秒
connection.setReadTimeout(2000);
// 是否打开输出流 true|false
connection.setDoOutput(true);
// 是否打开输入流true|false
connection.setDoInput(true);
// 提交方法POST|GET
connection.setRequestMethod("POST");
// 是否缓存true|false
connection.setUseCaches(false);
// 打开连接端口
connection.connect();
DataOutputStream out = new DataOutputStream(
// 打开输出流往对端服务器写数据
connection.getOutputStream());
// 写数据,也就是提交你的表单
out.writeBytes(content);
// 刷新
out.flush();
// 关闭输出流
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
// 往对端写完数据对端服务器返回数据
connection.getInputStream(), encoding));
// 以BufferedReader流来读取
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
// 关闭连接
connection.disconnect();
}
}
return "";
}
/**
* 测试
*/
public static void main(String[] args) {
AddressUtil addressUtils = new AddressUtil();
String ip = "106.19.100.234";
String address = "";
try {
address = addressUtils.getAddresses("ip=" + ip, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/** 输出:中国湖南省长沙市 */
System.out.println(address);
}
}