一、獲取客戶端ip的方法
//傳入request對(duì)象,獲得客戶端ip
//注意,本地不行,本地會(huì)獲取到0:0:0:0:0:0:0:1;服務(wù)器上是正常的
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)) {
//本地會(huì)獲取到0:0:0:0:0:0:0:1
ip = request.getRemoteAddr();
}
if (ip.contains(",")) {
return ip.split(",")[0];
} else {
return ip;
}
}
二、獲取服務(wù)器ip的方法
public static String getServerIP() {
String ip = null;
try {
//獲取當(dāng)前服務(wù)器ip
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
LOG.error("獲取當(dāng)前服務(wù)器ip報(bào)錯(cuò)", e);
}
return ip;
}
三、其它備注
1.可以用RestTemplate
發(fā)送http請(qǐng)求文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-503234.html
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
//這個(gè)是發(fā)送get請(qǐng)求,然后把返回報(bào)文轉(zhuǎn)為string類型
String htmlXml = restTemplate.getForObject("www.baidu.com", String.class);
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-503234.html
到了這里,關(guān)于Java后臺(tái)獲取客戶端ip與服務(wù)器ip的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!