java通过IP解析地理位置
生活随笔
收集整理的這篇文章主要介紹了
java通过IP解析地理位置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java通過IP解析地理位置
文章目錄
- java通過IP解析地理位置
- 一、獲取IP地址
- 二、百度普通IP定位API獲取地理位置
在項目開發中,需要在登錄日志或者操作日志中記錄客戶端ip所在的地理位置。目前根據ip定位地理位置的第三方api有好幾個,淘寶、新浪、百度等,這三種其實也有些缺點的:淘寶,開始幾次可以成功根據ip獲取對應地理位置,但后面就莫名其妙開始不行,直接通過瀏覽器獲取又可以;新浪,之前一直可以,但最近不知道為什么不行了,訪問直接報錯(可能api修改了或者取消了吧);百度,需要申請百度地圖開發者平臺的開發者賬號,請求時接口中需要加上百度提供的秘鑰等信息,好像不能定位國外的ip,但是針對國內的可以使用。在此整理一下,便于后期使用。
百度Web服務API-普通IP定位:http://lbsyun.baidu.com/index.php?title=webapi/ip-api
根據以上使用指南,注冊百度賬號,成為地圖開放平臺開發者,獲取密鑰(AK),根據服務文檔使用。
一、獲取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;}/*** 獲取本機的局域網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 {/*** 根據IP查詢地理位置* @param ip* 查詢的地址* @return status* 0:正常* 1:API查詢失敗* 2:API返回數據不完整* @throws IOException* @throws JSONException*/public static Object[] getLocation(String ip) throws IOException, JSONException {String lng = null;// 經度String lat = null;// 緯度String province=null;//省String city = null;// 城市名String status = "0";// 成功String ipString = null;String jsonData = ""; // 請求服務器返回的json字符串數據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協議 https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll //HTTPS協議*/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返回數據不完整}} 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數據格式。
{ 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解析地理位置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅谈算法——多项式乘法相关
- 下一篇: 举例说明语言接触会造成哪些结果_2008