JAVA从url中分离ip和port

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() );

}

}