Java根据请求的IP地址获取该请求的详细地址

Java根据请求的IP地址获取该请求的详细地址

  1. 在阿里云官网购买“全球IP归属地查询 - IP定位 - IP查询 - 支持高并发-毫秒级-免费”的服务。
  2. 购买完成后就可以在Java中开始编写代码调用服务了。首先创建地址类。
package com.example.demo.model;

import com.alibaba.fastjson.annotation.JSONField;

import lombok.Data;

/**
 * 
 * @Title: DetailedAddressParameter.java
 * @Description: 详细地址参数对象
 * @author: 
 * @date: 
 * @version: 
 */
@Data
public class DetailedAddressParameter {
	// 响应代码
	private int code;
	// 响应信息
	private String message;
	// ip地址
	private String ip;
	// 详细地址
	@JSONField(name = "result")
	private DetailedAddress detailedAddress;
}


/**
 * 
 * @Title: DetailedAddress.java
 * @Description: 详细地址对象
 * @author: 
 * @date: 
 * @version: 
 */
@Data
public class DetailedAddress {
	// 英文简称
	private String en_short;
	// 归属国家英文名称
	private String en_name;
	// 归属国家
	private String nation;
	// 归属省份
	private String province;
	// 归属城市
	private String city;
	// 归属县区
	private String district;
	// 归属地编码
	private long adcode;
	// 经度
	private double lat;
	// 维度
	private double lng;
}
  1. 新建一个工具类,类中提供获取请求ip地址的方法和根据ip地址获取详细地址的方法。
package com.example.demo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class CommonUtils {

	/**
	 * 
	 * @Title: getIpAddr
	 * @Description: 获取请求的ip地址
	 * @param request
	 * @return String
	 * @author: 
	 * @date: 
	 * @version: 
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
	
	/**
	 * 
	 * @Title: getDetailedAddress
	 * @Description: 获取请求的详细地址
	 * @param ip
	 * @return String
	 * @author: 
	 * @date: 
	 * @version: 
	 */
	public static String getDetailedAddress(String ip) {
		String host = "https://ips.market.alicloudapi.com"; // 【1】请求地址 支持http 和 https 及 WEBSOCKET
		String path = "/iplocaltion"; // 【2】后缀
		String appcode = "开通服务的AppCode"; // 【3】开通服务后 买家中心-查看AppCode
//		String ip = "127.0.0.1"; // 【4】请求参数,详见文档描述
		String urlSend = host + path + "?ip=" + ip; // 【5】拼接请求链接
		String json = null;
		try {
			URL url = new URL(urlSend);
			HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
			httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
			int httpCode = httpURLCon.getResponseCode();
			if (httpCode == 200) {
				json = read(httpURLCon.getInputStream());
				System.out.println("正常请求计费(其他均不计费)");
				System.out.println("获取返回的json:");
				System.out.print(json);
			} else {
				Map<String, List<String>> map = httpURLCon.getHeaderFields();
				String error = map.get("X-Ca-Error-Message").get(0);
				if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
					System.out.println("AppCode错误 ");
				} else if (httpCode == 400 && error.equals("Invalid Url")) {
					System.out.println("请求的 Method、Path 或者环境错误");
				} else if (httpCode == 400 && error.equals("Invalid Param Location")) {
					System.out.println("参数错误");
				} else if (httpCode == 403 && error.equals("Unauthorized")) {
					System.out.println("服务未被授权(或URL和Path不正确)");
				} else if (httpCode == 403 && error.equals("Quota Exhausted")) {
					System.out.println("套餐包次数用完 ");
				} else {
					System.out.println("参数名错误 或 其他错误");
					System.out.println(error);
				}
			}

		} catch (MalformedURLException e) {
			System.out.println("URL格式错误");
		} catch (UnknownHostException e) {
			System.out.println("URL地址错误");
		} catch (Exception e) {
			// 打开注释查看详细报错异常信息
			// e.printStackTrace();
		}
		return json;
	}

	/**
	 * 
	 * @Title: read
	 * @Description: 读取返回结果
	 * @param is
	 * @return
	 * @throws IOException String
	 * @author: 
	 * @date: 
	 * @version: 
	 */
	private static String read(InputStream is) throws IOException {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while ((line = br.readLine()) != null) {
			line = new String(line.getBytes(), "utf-8");
			sb.append(line);
		}
		br.close();
		return sb.toString();
	}
}

  1. 调用工具类中的接口
public String getAddress(HttpServletRequest request) {
	// 获取请求的ip地址
	String ipAddr = CommonUtils.getIpAddr(request);
	// 获取请求的详细地址
	String detailedAddress = CommonUtils.getDetailedAddress(ipAddr);
	// JSON字符串转为JSON对象
	DetailedAddressParameter detailedAddressParameter = JSON.parseObject(detailedAddress,
			DetailedAddressParameter.class);
	DetailedAddress detailedAddress2 = detailedAddressParameter.getDetailedAddress();
	String address = "";
	if (detailedAddress2.getNation() != null) {
		// 归属国家
		String nation = detailedAddress2.getNation();
		// 归属省份
		String province = detailedAddress2.getProvince();
		// 归属城市
		String city = detailedAddress2.getCity();
		// 归属县区
		String district = detailedAddress2.getDistrict();
		address = nation + province + city + district;
	} else {
		address = detailedAddressParameter.getMessage();
	}
	return address;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值