码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA从url中分离ip和port

时间:2017-06-19 12:52:51      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:replace   return   false   parse   pil   []   java   int   trim   

public class NetAddrUtil {
/**
* 从url中分析出hostIP<br/>
* @param url
* @author wull
* @return
*/
public static String getIpFromUrl(String url) {
// 1.判断是否为空
if (url == null || url.trim().equals("")) {
return "";
}

// 2. 如果是以localhost,那么替换成127.0.0.1
if(url.startsWith("http://" + C.Net.LOCALHOST_STR) ){
url = url.replace("http://" + C.Net.LOCALHOST_STR, "http://" + C.Net.LOCALHOST_NUM) ;
}

String host = "";
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
Matcher matcher = p.matcher(url);
if (matcher.find()) {
host = matcher.group();
}
return host;
}

/**
* 从url中分析出hostIP:PORT<br/>
* @param url
* @author wull */
public static IpPortAddr getIpPortFromUrl(String url) {
// 1.判断是否为空
if (url == null || url.trim().equals("")) {
return null;
}

// 2. 如果是以localhost,那么替换成127.0.0.1
if(url.startsWith("http://" + C.Net.LOCALHOST_STR) ){
url = url.replace("http://" + C.Net.LOCALHOST_STR, "http://" + C.Net.LOCALHOST_NUM) ;
}

String host = "";
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+(:\\d{0,5})?");
Matcher matcher = p.matcher(url);
if (matcher.find()) {
host = matcher.group() ;
}

// 如果
if(host.contains(":") == false){
return new IpPortAddr(host, 80 );
}

String[] ipPortArr = host.split(":");
return new IpPortAddr(ipPortArr[0] , ConfigUtil.parseInt( ipPortArr[1] ));
}

public static void main(String [] args){
String url = "http://10.33.32.81:8080/login.action";
System.out.println(NetAddrUtil.getIpFromUrl(url) );
IpPortAddr addr= NetAddrUtil.getIpPortFromUrl(url) ;
System.out.println(addr.getIp() +"=========>" +addr.getPort() );
}
}

JAVA从url中分离ip和port

标签:replace   return   false   parse   pil   []   java   int   trim   

原文地址:http://www.cnblogs.com/histlyb/p/7047899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!