まずはクライアントIPの取得方法
//传入request对象,获得客户端ip
//注意,本地不行,本地会获取到0:0:0:0:0:0:0:1;服务器上是正常的
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//本地会获取到0:0:0:0:0:0:0:1
ip = request.getRemoteAddr();
}
if (ip.contains(",")) {
return ip.split(",")[0];
} else {
return ip;
}
}
第二に、サーバーのIPを取得する方法
public static String getServerIP() {
String ip = null;
try {
//获取当前服务器ip
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
LOG.error("获取当前服务器ip报错", e);
}
return ip;
}
3. その他の注意事項
1. RestTemplate
http リクエストを送信できます
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
//这个是发送get请求,然后把返回报文转为string类型
String htmlXml = restTemplate.getForObject("www.baidu.com", String.class);