最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java如何通過IP解析地理位置

 更新時間:2023年02月13日 15:14:53   作者:GeGe&YoYo  
這篇文章主要介紹了java如何通過IP解析地理位置的實(shí)例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

java通過IP解析地理位置

在項(xiàng)目開發(fā)中,需要在登錄日志或者操作日志中記錄客戶端ip所在的地理位置。

目前根據(jù)ip定位地理位置的第三方api有好幾個,淘寶、新浪、百度等,這三種其實(shí)也有些缺點(diǎn)的:

  • 淘寶,開始幾次可以成功根據(jù)ip獲取對應(yīng)地理位置,但后面就莫名其妙開始不行,直接通過瀏覽器獲取又可以;
  • 新浪,之前一直可以,但最近不知道為什么不行了,訪問直接報(bào)錯(可能api修改了或者取消了吧);
  • 百度,需要申請百度地圖開發(fā)者平臺的開發(fā)者賬號,請求時接口中需要加上百度提供的秘鑰等信息,好像不能定位國外的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();
		}
		
	    /*
	     * 請求URL
	    	http://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),此處換成自己的AK
		String url = String.format("https://api.map.baidu.com/location/ip?ak=%s&ip=%s&coor=bd09ll", key, ipString);// 百度普通IP定位API
		URL 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)碼  
}

java獲取IP歸屬地(省、市)

1、添加依賴

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

2、工具類代碼

package com.shucha.deveiface.biz.test;
 
 
/**
 * @author tqf
 * @Description 根據(jù)ip獲取歸屬地
 * @Version 1.0
 * @since 2022-05-27 10:11
 */
 
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
public class iptes {
    private static Logger logger = LoggerFactory.getLogger(iptes.class);
 
    /**
     * 獲取IP地址
     *
     * 使用Nginx等反向代理軟件, 則不能通過request.getRemoteAddr()獲取IP地址
     * 如果使用了多級反向代理的話,X-Forwarded-For的值并不止一個,而是一串IP地址,X-Forwarded-For中第一個非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);
        }
 
        //使用代理,則獲取第一個IP地址
        if(StringUtils.isEmpty(ip) ) {
            if(ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
 
        return ip;
    }
 
    /**
     * 根據(jù)ip獲取歸屬地
     * @param ip
     * @return
     */
    public static IpAddress getAddress(String ip) {
        String url = "http://ip.ws.126.net/ipquery?ip=" + ip;
        String str = HttpUtil.get(url);
        if(!StrUtil.hasBlank(str)){
            String substring = str.substring(str.indexOf("{"), str.indexOf("}")+1);
            JSONObject jsonObject = JSON.parseObject(substring);
            String province = jsonObject.getString("province");
            String city = jsonObject.getString("city");
            IpAddress ipAddress = new IpAddress();
            ipAddress.setProvince(province);
            ipAddress.setCity(city);
            System.out.println("ip:"+ ip + ",省份:" + province + ",城市:" + city);
            return ipAddress;
        }
        return null;
    }
 
    @Data
    public static class IpAddress{
        private String province;
        private String city;
    }
 
    public static void main(String[] args) {
        System.out.println(getAddress("36.25.225.250"));
    }
 
}

3、測試結(jié)果

測試ip:36.25.225.250

返回?cái)?shù)據(jù):

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

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

總結(jié)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解

    Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解

    今天小編就為大家分享一篇關(guān)于Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • java短信驗(yàn)證碼獲取次數(shù)限制實(shí)例

    java短信驗(yàn)證碼獲取次數(shù)限制實(shí)例

    這篇文章主要介紹了java短信驗(yàn)證碼獲取次數(shù)限制實(shí)例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • 深入理解spring的AOP機(jī)制原理

    深入理解spring的AOP機(jī)制原理

    本篇文章主要介紹了深入理解spring的AOP機(jī)制原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • spring boot openfeign從此和httpClient說再見詳析

    spring boot openfeign從此和httpClient說再見詳析

    這篇文章主要給大家介紹了關(guān)于spring boot openfeign從此和httpClient說再見的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧
    2018-06-06
  • Windows 10上JDK環(huán)境安裝配置圖文教程

    Windows 10上JDK環(huán)境安裝配置圖文教程

    這篇文章主要為大家詳細(xì)介紹了Windows 10上JDK環(huán)境安裝配置圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • java實(shí)體對象與Map之間的轉(zhuǎn)換工具類代碼實(shí)例

    java實(shí)體對象與Map之間的轉(zhuǎn)換工具類代碼實(shí)例

    這篇文章主要介紹了java實(shí)體對象與Map之間的轉(zhuǎn)換工具類代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12
  • 一文讀懂Spring中@Bean注解的核心作用

    一文讀懂Spring中@Bean注解的核心作用

    快速了解Spring框架中的@Bean注解?本文將帶你一鍵掌握其核心作用!只需一篇短文,揭示@Bean注解如何在Spring中定義bean實(shí)例,以及管理和裝配Bean的奧秘,閱讀指南,讓Spring開發(fā)更加得心應(yīng)手!
    2024-01-01
  • 淺談JAVA 類加載器

    淺談JAVA 類加載器

    這篇文章主要介紹了JAVA 類加載器的的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-06-06
  • MyBatis學(xué)習(xí)教程(五)-實(shí)現(xiàn)關(guān)聯(lián)表查詢方法詳解

    MyBatis學(xué)習(xí)教程(五)-實(shí)現(xiàn)關(guān)聯(lián)表查詢方法詳解

    本文給大家介紹mybatis關(guān)聯(lián)查詢,包括一對一關(guān)聯(lián)查詢,一對多關(guān)聯(lián)查詢,代碼簡單易懂,感興趣的朋友一起學(xué)習(xí)吧
    2016-05-05
  • Mac使用Idea配置傳統(tǒng)SSM項(xiàng)目(非maven項(xiàng)目)

    Mac使用Idea配置傳統(tǒng)SSM項(xiàng)目(非maven項(xiàng)目)

    本文主要介紹了Mac使用Idea配置傳統(tǒng)SSM項(xiàng)目(非maven項(xiàng)目),將展示如何設(shè)置項(xiàng)目結(jié)構(gòu)、添加依賴關(guān)系等,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01

最新評論

漯河市| 安岳县| 扬州市| 定州市| 沁阳市| 双牌县| 萨迦县| 棋牌| 兰考县| 阳新县| 上栗县| 九江县| 泉州市| 二连浩特市| 石城县| 确山县| 德安县| 科技| 宜良县| 漳州市| 固安县| 云林县| 江北区| 平阴县| 旬阳县| 恩平市| 南投县| 清丰县| 佛学| 泰安市| 乌兰县| 涟源市| 高台县| 黔江区| 哈密市| 电白县| 崇礼县| 石泉县| 仙游县| 邵阳县| 五大连池市|