java怎么通过IP解析地理位置(IP,java,开发技术)

时间:2024-04-29 00:12:23 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

    java通过IP解析地理位置

    在项目开发中,需要在登录日志或者操作日志中记录客户端ip所在的地理位置。

    目前根据ip定位地理位置的第三方api有好几个,淘宝、新浪、百度等,这三种其实也有些缺点的:

    • 淘宝,开始几次可以成功根据ip获取对应地理位置,但后面就莫名其妙开始不行,直接通过浏览器获取又可以;

    • 新浪,之前一直可以,但最近不知道为什么不行了,访问直接报错(可能api修改了或者取消了吧);

    • 百度,需要申请百度地图开发者平台的开发者账号,请求时接口中需要加上百度提供的秘钥等信息,好像不能定位国外的ip,但是针对国内的可以使用。

    获取IP地址

    java IP地址工具类,java IP地址获取,java获取客户端IP地址

    importjava.net.Inet4Address;importjava.net.InetAddress;importjava.net.NetworkInterface;importjava.util.Enumeration;importjavax.servlet.http.HttpServletRequest;publicclassIpUtils{ privatestaticfinalString[]HEADERS={"X-Forwarded-For","Proxy-Client-IP","WL-Proxy-Client-IP","HTTP_X_FORWARDED_FOR","HTTP_X_FORWARDED","HTTP_X_CLUSTER_CLIENT_IP","HTTP_CLIENT_IP","HTTP_FORWARDED_FOR","HTTP_FORWARDED","HTTP_VIA","REMOTE_ADDR","X-Real-IP" }; /** *判断ip是否为空,空返回true *@paramip *@return */ publicstaticbooleanisEmptyIp(finalStringip){return(ip==null||ip.length()==0||ip.trim().equals("")||"unknown".equalsIgnoreCase(ip));} /** *判断ip是否不为空,不为空返回true *@paramip *@return */ publicstaticbooleanisNotEmptyIp(finalStringip){return!isEmptyIp(ip);} /****获取客户端ip地址(可以穿透代理)*@paramrequestHttpServletRequest*@return*/publicstaticStringgetIpAddress(HttpServletRequestrequest){ Stringip=""; for(Stringheader:HEADERS){ip=request.getHeader(header);if(isNotEmptyIp(ip)){ break;}}if(isEmptyIp(ip)){ ip=request.getRemoteAddr();}if(isNotEmptyIp(ip)&&ip.contains(",")){ ip=ip.split(",")[0];}if("0:0:0:0:0:0:0:1".equals(ip)){ip="127.0.0.1";}returnip;}/** *获取本机的局域网ip地址,兼容Linux *@returnString *@throwsException */ publicStringgetLocalHostIP()throwsException{ Enumeration<NetworkInterface>allNetInterfaces=NetworkInterface.getNetworkInterfaces(); StringlocalHostAddress=""; while(allNetInterfaces.hasMoreElements()){ NetworkInterfacenetworkInterface=allNetInterfaces.nextElement(); Enumeration<InetAddress>address=networkInterface.getInetAddresses(); while(address.hasMoreElements()){ InetAddressinetAddress=address.nextElement(); if(inetAddress!=null&&inetAddressinstanceofInet4Address){ localHostAddress=inetAddress.getHostAddress(); } } } returnlocalHostAddress; }}

    百度普通IP定位API获取地理位置

    importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.UnsupportedEncodingException;importjava.net.MalformedURLException;importjava.net.URL;importjava.net.URLConnection;importorg.json.JSONException;importorg.json.JSONObject;publicclassIp2LocationViaBaidu{ /** *根据IP查询地理位置 *@paramip *查询的地址 *@returnstatus * 0:正常 * 1:API查询失败 * 2:API返回数据不完整 *@throwsIOException *@throwsJSONException */ publicstaticObject[]getLocation(Stringip)throwsIOException,JSONException{ Stringlng=null;//经度 Stringlat=null;//纬度 Stringprovince=null;//省 Stringcity=null;//城市名 Stringstatus="0";//成功 StringipString=null; StringjsonData="";//请求服务器返回的json字符串数据 try{ ipString=java.net.URLEncoder.encode(ip,"UTF-8"); }catch(UnsupportedEncodingExceptione1){ e1.printStackTrace(); } /* *请求URL http://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll//HTTP协议 https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll//HTTPS协议 */ Stringkey="*************";//百度密钥(AK),此处换成自己的AK Stringurl=String.format("https://api.map.baidu.com/location/ip?ak=%s&ip=%s&coor=bd09ll",key,ipString);//百度普通IP定位API URLmyURL=null; URLConnectionhttpsConn=null; try{ myURL=newURL(url); }catch(MalformedURLExceptione){ e.printStackTrace(); } InputStreamReaderinsr=null; BufferedReaderbr=null; try{ httpsConn=(URLConnection)myURL.openConnection();//不使用代理 if(httpsConn!=null){ insr=newInputStreamReader(httpsConn.getInputStream(),"UTF-8"); br=newBufferedReader(insr); Stringdata=null; intcount=1; while((data=br.readLine())!=null){ jsonData+=data; } JSONObjectjsonObj=newJSONObject(jsonData); if("0".equals(jsonObj.getString("status"))){ province=jsonObj.getJSONObject("content").getJSONObject("address_detail").getString("province"); city=jsonObj.getJSONObject("content").getJSONObject("address_detail").getString("city"); lng=jsonObj.getJSONObject("content").getJSONObject("point").getString("x"); lat=jsonObj.getJSONObject("content").getJSONObject("point").getString("y"); if(city.isEmpty()||lng.isEmpty()||lat.isEmpty()){ status="2";//API返回数据不完整 } }else{ status="1";//API查询失败 } } }catch(IOExceptione){ e.printStackTrace(); }finally{ if(insr!=null){ insr.close(); } if(br!=null){ br.close(); } } returnnewObject[]{status,province,city,lng,lat}; }}

    把上边的百度密钥换成你自己的,下边是API返回的json数据格式。

    {address:"CN|北京|北京|None|CHINANET|1|None",#地址content:#详细内容{address:"北京市",#简要地址address_detail:#详细地址信息{city:"北京市",#城市city_code:131,#百度城市代码district:"",#区县province:"北京市",#省份street:"",#街道street_number:""#门址},point:#当前城市中心点{x:"116.39564504",y:"39.92998578"}},status:0#返回状态码}

    java获取IP归属地(省、市)

    1、添加依赖

    <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.3</version></dependency>

    2、工具类代码

    packagecom.shucha.deveiface.biz.test;/***@authortqf*@Description根据ip获取归属地*@Version1.0*@since2022-05-2710:11*/importcn.hutool.core.util.StrUtil;importcn.hutool.http.HttpUtil;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.itextpdf.text.log.Logger;importcom.itextpdf.text.log.LoggerFactory;importlombok.Data;importorg.apache.commons.lang3.StringUtils;importjavax.servlet.http.HttpServletRequest;publicclassiptes{privatestaticLoggerlogger=LoggerFactory.getLogger(iptes.class);/***获取IP地址**使用Nginx等反向代理软件,则不能通过request.getRemoteAddr()获取IP地址*如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址*/publicstaticStringgetIpAddr(HttpServletRequestrequest){Stringip=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(Exceptione){logger.error("IPUtilsERROR",e);}//使用代理,则获取第一个IP地址if(StringUtils.isEmpty(ip)){if(ip.indexOf(",")>0){ip=ip.substring(0,ip.indexOf(","));}}returnip;}/***根据ip获取归属地*@paramip*@return*/publicstaticIpAddressgetAddress(Stringip){Stringurl="http://ip.ws.126.net/ipquery?ip="+ip;Stringstr=HttpUtil.get(url);if(!StrUtil.hasBlank(str)){Stringsubstring=str.substring(str.indexOf("{"),str.indexOf("}")+1);JSONObjectjsonObject=JSON.parseObject(substring);Stringprovince=jsonObject.getString("province");Stringcity=jsonObject.getString("city");IpAddressipAddress=newIpAddress();ipAddress.setProvince(province);ipAddress.setCity(city);System.out.println("ip:"+ip+",省份:"+province+",城市:"+city);returnipAddress;}returnnull;}@DatapublicstaticclassIpAddress{privateStringprovince;privateStringcity;}publicstaticvoidmain(String[]args){System.out.println(getAddress("36.25.225.250"));}}

    3、测试结果

    测试ip:36.25.225.250

    返回数据:

    ip:36.25.225.250,省份:浙江省,城市:湖州市

    iptes.IpAddress(province=浙江省, city=湖州市)

    java怎么通过IP解析地理位置

     </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
    本文:java怎么通过IP解析地理位置的详细内容,希望对您有所帮助,信息来源于网络。
    上一篇:C++右值引用与移动构造函数应用的方法是什么下一篇:

    1 人围观 / 0 条评论 ↓快速评论↓

    (必须)

    (必须,保密)

    阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18