由于有时候Web项目作为外部API调用时,每次启动都要先查一下IP,拼接项目名,然后呼叫该URL,很繁琐。因此写了一个小程序,用于Web项目获取内网URL,作为公用类,测试阶段很实用。如果访问不了局域网tomcat下的项目,可以看我另一篇博客,有详细说明。
地址:http://blog.youkuaiyun.com/womeng2009/article/details/53513731
下面是Java源代码:
package com.GetIP;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
/*
* 功能说明:获取Web工程内网访问URL
* 开发者:Jiro.Chen
* 时间:2016-12-14 10:40:12
* */
public class GetWebProUrl {
public static String getLocalHostIP(){
String result = null;
try {
InetAddress IP = Inet4Address.getLocalHost();
String ip = IP.toString();
int index = ip.indexOf('/');
result = ip.substring(index+1, ip.length());
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String getProjectURL(String IP){
String result = "http://";
result += IP;
result += ":8080/";
String proPath = System.getProperty("user.dir");
String proName = proPath.substring(proPath.lastIndexOf("\\")+1, proPath.length());
result += proName;
return result;
}
public static void main(String[] args) {
String localhostIP = GetWebProUrl.getLocalHostIP();
String ProjectURL = GetWebProUrl.getProjectURL(localhostIP);
System.out.println(ProjectURL);
}
}
输出示例:
http://192.168.1.80:8080/EDUToHome