After searching everywhere including StackOverflow. I found this:
to get host:
String host = InetAddress.getLocalHost().getHostName();
to get port:
// In your application.properties
server.port=8080
String port = environment.getProperty("server.port");
I have also written an example class on it.
import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ApiUrl {
private final Environment environment;
public static final String apiUrlPrefix = "/api";
public static final String apiVersion = "/v1";
public ApiUrl(Environment environment) {
this.environment = environment;
}
public String getApiBaseUrl() throws UnknownHostException {
String host = InetAddress.getLocalHost().getHostName();
String port = environment.getProperty("server.port");
return "https://" + host +":"+ port + apiUrlPrefix + apiVersion;
}
}
I hope this might help people.
References for more study:
https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html