Java根据请求的IP地址获取该请求的详细地址
- 在阿里云官网购买“全球IP归属地查询 - IP定位 - IP查询 - 支持高并发-毫秒级-免费”的服务。
- 购买完成后就可以在Java中开始编写代码调用服务了。首先创建地址类。
package com.example.demo.model;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
@Data
public class DetailedAddressParameter {
private int code;
private String message;
private String ip;
@JSONField(name = "result")
private DetailedAddress detailedAddress;
}
@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;
}
- 新建一个工具类,类中提供获取请求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 {
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")) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
public static String getDetailedAddress(String ip) {
String host = "https://ips.market.alicloudapi.com";
String path = "/iplocaltion";
String appcode = "开通服务的AppCode";
String urlSend = host + path + "?ip=" + ip;
String json = null;
try {
URL url = new URL(urlSend);
HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
httpURLCon.setRequestProperty("Authorization", "APPCODE " + 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) {
}
return json;
}
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();
}
}
- 调用工具类中的接口
public String getAddress(HttpServletRequest request) {
String ipAddr = CommonUtils.getIpAddr(request);
String detailedAddress = CommonUtils.getDetailedAddress(ipAddr);
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;
}