根据IP地址查询物理位置(IP地址定位库)并且查询当前地址的天气信息(中国气象网)
生活随笔
收集整理的這篇文章主要介紹了
根据IP地址查询物理位置(IP地址定位库)并且查询当前地址的天气信息(中国气象网)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
有的時(shí)候我們需要查詢?cè)L問我們系統(tǒng)的IP的地址,并且記錄下訪問IP的物理地址。但是用接口調(diào)用不穩(wěn)定,如:淘寶的地址
http://ip.taobao.com/service/getIpInfo.php?ip=180.169.29.21所以我們提供一個(gè)IP定位庫(kù)。
首先,提供一個(gè)jar包。
compile group: 'org.lionsoul', name: 'ip2region', version: '1.7.2'并且提供定位庫(kù):
參考地址:https://blog.51cto.com/14309075/2390060
其次:查找用戶的IP。
/*** 獲取IP地址** 使用Nginx等反向代理軟件, 則不能通過request.getRemoteAddr()獲取IP地址* 如果使用了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP地址,X-Forwarded-For中第一個(gè)非unknown的有效IP字符串,則為真實(shí)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地址后,這樣我們根據(jù)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地址* 如果使用了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP地址,X-Forwarded-For中第一個(gè)非unknown的有效IP字符串,則為真實(shí)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);}// 使用代理,則獲取第一個(gè)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地址* 如果使用了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP地址,X-Forwarded-For中第一個(gè)非unknown的有效IP字符串,則為真實(shí)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;}/*** 根據(jù)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 //Memorytry {DbConfig config = new DbConfig();DbSearcher searcher = new DbSearcher(config, dbPath);//define the methodMethod 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");} }最后。根據(jù)地址信息查詢天氣信息
@CrossOrigin(origins = "*")@ApiOperation(value="今日天氣")@RequestMapping(name = "今日天氣", value = {"/todayWeather"}, method = RequestMethod.GET)public Result todayWeather(HttpServletRequest request)throws Exception{//根據(jù)ip查詢當(dāng)前地址String ip= IPUtils.getIpAddr(request);//根據(jù)ip查詢當(dāng)前地址/*String addressUrl="http://ip.taobao.com/service/getIpInfo.php?ip=";logger.info("當(dāng)前機(jī)器的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("當(dāng)前地址信息是:"+addressInfo);}*///根據(jù)IP地址查詢IP所在位置String address=IPUtils.getAddress(ip);logger.info("ip地址====>"+address);String cityId=null;if(address!=null&&!address.contains("內(nèi)網(wǎng)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<>();//查詢天氣1String 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/";//當(dāng)前城市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"));//當(dāng)前天氣weatherMap.put("weather",weatherinfo.get("weather"));}else{return Result.failure("今日天氣失敗");}//查詢天氣2String 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());//當(dāng)前溫度weatherMap.put("temp",weatherinfo1.get("temp"));//風(fēng)向weatherMap.put("WD",weatherinfo1.get("WD"));//風(fēng)級(jí)weatherMap.put("WS",weatherinfo1.get("WS"));//相對(duì)濕度SDweatherMap.put("SD",weatherinfo1.get("SD"));return Result.ok("查詢天氣成功",weatherMap);}else{return Result.failure("今日天氣失敗");}}?
總結(jié)
以上是生活随笔為你收集整理的根据IP地址查询物理位置(IP地址定位库)并且查询当前地址的天气信息(中国气象网)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 地图搜索商家,检索关键字
- 下一篇: python神经网络算法pdf_深度学习