IP获取归属地区
使用 http://whois.pconline.com.cn/ipJson.jsp 这个 URL 来获取 IP 地址的归属城市信息
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IpAddressUtils {
private static final Logger log = LoggerFactory.getLogger(IpAddressUtils.class);
/**
* 获取当前网络ip
*
* @param request
* @return
*/
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) {
log.error("Error occurred when getIpAddr method was invoked.ex:", e);
}
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;
}
/**
* IP获取归属地区
* @param ipAddress
* @return
*/
public static String getAddress(String ipAddress) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String address = null;
try {
// 创建 HttpClient 实例
httpClient = HttpClients.createDefault();
// 构建 API 请求 URL
String apiUrl = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ipAddress;
// 创建 HttpGet 请求
HttpGet httpGet = new HttpGet(apiUrl);
// 发送请求并获取响应
response = httpClient.execute(httpGet);
// 解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String jsonResponse = EntityUtils.toString(response.getEntity(), "GBK");
address = jsonResponse.substring(jsonResponse.indexOf("addr") + 7, jsonResponse.indexOf("regionNames") - 3);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(httpClient, response);
return address;
}
}
public static void close(CloseableHttpClient httpClient, CloseableHttpResponse response) {
try {
if (Objects.nonNull(response)) {
response.close();
}
if(Objects.nonNull(httpClient)){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}