有的时候我们需要查询访问我们系统的IP的地址,并且记录下访问IP的物理地址。但是用接口调用不稳定,如:淘宝的地址
http://ip.taobao.com/service/getIpInfo.php?ip=180.169.29.21
所以我们提供一个IP定位库。
首先,提供一个jar包。
compile group: 'org.lionsoul', name: 'ip2region', version: '1.7.2'
并且提供定位库:
参考地址:https://blog.51cto.com/14309075/2390060
其次:查找用户的IP。
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
return ip;
}
查询出IP地址后,这样我们根据IP地址查询物理地址。
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Method;
/**
* IP地址
*/
public class IPUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
/**
* 获取IP地址
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr() {
String ip = null;
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
// 使用代理,则获取第一个IP地址
if (StringUtils.isNotEmpty(ip) && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
return ip;
}
/**
* 根据IP地址查询所在物理位置
*
* @param ip
* @return
*/
public static String getAddress(String ip){
String dbPath = IPUtils.class.getResource("/ip2region.db").getPath();
File file = new File(dbPath);
if ( file.exists() == false ) {
System.out.println("Error: Invalid ip2region.db file");
}
//查询算法
int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
//DbSearcher.BINARY_ALGORITHM //Binary
//DbSearcher.MEMORY_ALGORITYM //Memory
try {
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, dbPath);
//define the method
Method method = null;
switch ( algorithm )
{
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
DataBlock dataBlock = null;
if ( Util.isIpAddress(ip) == false ) {
logger.error("Error: Invalid ip address");
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
String address=dataBlock.getRegion();
System.out.println("address====>"+address);
String countryName=address.substring(0,2);
String provinceName=address.substring(5,8);
String cityName=address.substring(9,12);
System.out.println("countryName="+countryName+",provinceName="+provinceName+",cityName="+cityName);
return dataBlock.getRegion();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
getAddress("42.203.192.25");
}
}
最后。根据地址信息查询天气信息
@CrossOrigin(origins = "*")
@ApiOperation(value="今日天气")
@RequestMapping(name = "今日天气", value = {"/todayWeather"}, method = RequestMethod.GET)
public Result todayWeather(HttpServletRequest request)throws Exception{
//根据ip查询当前地址
String ip= IPUtils.getIpAddr(request);
//根据ip查询当前地址
/*String addressUrl="http://ip.taobao.com/service/getIpInfo.php?ip=";
logger.info("当前机器的ip地址是:"+ip);
if(ip!=null){
addressUrl+=ip;
}else{
addressUrl= "http://ip.taobao.com/service/getIpInfo.php?ip=180.169.29.210";
}
Response addressResponse=OkHttpUtils.get(addressUrl);
ResponseBody addressResponseBody=addressResponse.body();
if(addressResponse.isSuccessful()&&addressResponseBody!=null){
String addressInfo=addressResponseBody.string();
logger.info("当前地址信息是:"+addressInfo);
}*/
//根据IP地址查询IP所在位置
String address=IPUtils.getAddress(ip);
logger.info("ip地址====>"+address);
String cityId=null;
if(address!=null&&!address.contains("内网IP")){
String cityName=address.substring(9,12);
List<SysArea> sysAreas=sysAreaService.getAreas(cityName);
if(sysAreas!=null&&sysAreas.size()>0){
cityId=sysAreas.get(0).getCityId();
}else{
cityId="101021300";
}
}else{
cityId="101021300";
}
Map<String,Object> weatherMap=new HashMap<>();
//查询天气1
String url="http://www.weather.com.cn/data/cityinfo/"+cityId+".html";
Response response=OkHttpUtils.get(url);
ResponseBody responseBody=response.body();
if(response.isSuccessful()&&responseBody!=null){
String info=responseBody.string();
JSONObject jsonObject=JSONObject.parseObject(info);
JSONObject weatherinfo=JSONObject.parseObject(jsonObject.get("weatherinfo").toString());
String imgUrl="http://www.weather.com.cn/m2/i/icon_weather/29x20/";
//当前城市
weatherMap.put("city",weatherinfo.get("city"));
//天气图片
weatherMap.put("pic1",imgUrl+weatherinfo.get("img1"));
weatherMap.put("pic2",imgUrl+weatherinfo.get("img2"));
//天气范围
weatherMap.put("tempRegion",weatherinfo.get("temp1")+"--"+weatherinfo.get("temp2"));
//当前天气
weatherMap.put("weather",weatherinfo.get("weather"));
}else{
return Result.failure("今日天气失败");
}
//查询天气2
String url1="http://www.weather.com.cn/data/sk/101010100.html";
Response response1=OkHttpUtils.get(url1);
ResponseBody responseBody1=response1.body();
if(response1.isSuccessful()&&responseBody1!=null){
String info=responseBody1.string();
JSONObject jsonObject1=JSONObject.parseObject(info);
JSONObject weatherinfo1=JSONObject.parseObject(jsonObject1.get("weatherinfo").toString());
//当前温度
weatherMap.put("temp",weatherinfo1.get("temp"));
//风向
weatherMap.put("WD",weatherinfo1.get("WD"));
//风级
weatherMap.put("WS",weatherinfo1.get("WS"));
//相对湿度SD
weatherMap.put("SD",weatherinfo1.get("SD"));
return Result.ok("查询天气成功",weatherMap);
}else{
return Result.failure("今日天气失败");
}
}