日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java通过IP解析地理位置

發(fā)布時(shí)間:2024/5/8 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java通过IP解析地理位置 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

java通過IP解析地理位置


文章目錄

  • java通過IP解析地理位置
    • 一、獲取IP地址
    • 二、百度普通IP定位API獲取地理位置


在項(xiàng)目開發(fā)中,需要在登錄日志或者操作日志中記錄客戶端ip所在的地理位置。目前根據(jù)ip定位地理位置的第三方api有好幾個(gè),淘寶、新浪、百度等,這三種其實(shí)也有些缺點(diǎn)的:淘寶,開始幾次可以成功根據(jù)ip獲取對應(yīng)地理位置,但后面就莫名其妙開始不行,直接通過瀏覽器獲取又可以;新浪,之前一直可以,但最近不知道為什么不行了,訪問直接報(bào)錯(cuò)(可能api修改了或者取消了吧);百度,需要申請百度地圖開發(fā)者平臺的開發(fā)者賬號,請求時(shí)接口中需要加上百度提供的秘鑰等信息,好像不能定位國外的ip,但是針對國內(nèi)的可以使用。在此整理一下,便于后期使用。

百度Web服務(wù)API-普通IP定位:http://lbsyun.baidu.com/index.php?title=webapi/ip-api

根據(jù)以上使用指南,注冊百度賬號,成為地圖開放平臺開發(fā)者,獲取密鑰(AK),根據(jù)服務(wù)文檔使用。

一、獲取IP地址

java IP地址工具類,java IP地址獲取,java獲取客戶端IP地址

import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration;import javax.servlet.http.HttpServletRequest;public class IpUtils {private static final String[] 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* @param ip* @return*/public static boolean isEmptyIp(final String ip){return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip));}/*** 判斷ip是否不為空,不為空返回true* @param ip* @return*/public static boolean isNotEmptyIp(final String ip){return !isEmptyIp(ip);}/**** 獲取客戶端ip地址(可以穿透代理)* @param request HttpServletRequest* @return*/public static String getIpAddress(HttpServletRequest request) {String ip = "";for (String header : 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";}return ip;}/*** 獲取本機(jī)的局域網(wǎng)ip地址,兼容Linux* @return String* @throws Exception*/public String getLocalHostIP() throws Exception{Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();String localHostAddress = "";while(allNetInterfaces.hasMoreElements()){NetworkInterface networkInterface = allNetInterfaces.nextElement();Enumeration<InetAddress> address = networkInterface.getInetAddresses();while(address.hasMoreElements()){InetAddress inetAddress = address.nextElement();if(inetAddress != null && inetAddress instanceof Inet4Address){localHostAddress = inetAddress.getHostAddress();}}}return localHostAddress;} }

二、百度普通IP定位API獲取地理位置

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;import org.json.JSONException; import org.json.JSONObject;public class Ip2LocationViaBaidu {/*** 根據(jù)IP查詢地理位置* @param ip* 查詢的地址* @return status* 0:正常* 1:API查詢失敗* 2:API返回?cái)?shù)據(jù)不完整* @throws IOException* @throws JSONException*/public static Object[] getLocation(String ip) throws IOException, JSONException {String lng = null;// 經(jīng)度String lat = null;// 緯度String province=null;//省String city = null;// 城市名String status = "0";// 成功String ipString = null;String jsonData = ""; // 請求服務(wù)器返回的json字符串?dāng)?shù)據(jù)try {ipString = java.net.URLEncoder.encode(ip, "UTF-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}/** 請求URLhttp://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll //HTTP協(xié)議 https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll //HTTPS協(xié)議*/String key = "*************";// 百度密鑰(AK),此處換成自己的AKString url = String.format("https://api.map.baidu.com/location/ip?ak=%s&ip=%s&coor=bd09ll", key, ipString);// 百度普通IP定位APIURL myURL = null;URLConnection httpsConn = null;try {myURL = new URL(url);} catch (MalformedURLException e) {e.printStackTrace();}InputStreamReader insr = null;BufferedReader br = null;try {httpsConn = (URLConnection) myURL.openConnection();// 不使用代理if (httpsConn != null) {insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");br = new BufferedReader(insr);String data = null;int count = 1;while ((data = br.readLine()) != null) {jsonData += data;}JSONObject jsonObj = new JSONObject(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返回?cái)?shù)據(jù)不完整}} else {status = "1";// API查詢失敗}}} catch (IOException e) {e.printStackTrace();} finally {if (insr != null) {insr.close();}if (br != null) {br.close();}}return new Object[] { status, province, city, lng, lat };} }

把上邊的百度密鑰換成你自己的,下邊是API返回的json數(shù)據(jù)格式。

{ address: "CN|北京|北京|None|CHINANET|1|None", #地址 content: #詳細(xì)內(nèi)容 { address: "北京市", #簡要地址 address_detail: #詳細(xì)地址信息 { city: "北京市", #城市 city_code: 131, #百度城市代碼 district: "", #區(qū)縣 province: "北京市", #省份 street: "", #街道 street_number: "" #門址 }, point: #當(dāng)前城市中心點(diǎn) { x: "116.39564504", y: "39.92998578" } }, status: 0 #返回狀態(tài)碼 }

回到頂部


總結(jié)

以上是生活随笔為你收集整理的java通过IP解析地理位置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。