0

I have found similar questions in StackOverflow but there are no accepted answers.

get application domain + port and path programmatically in spring?

I want to send an email verification link. For example: https://host:port/path?encrypted_email=encrypted-data-of-user-email

I want to send this URL to the user's email from the signup controller. But I won't write the Http/https, host, port, and path of verifying email hardcoded. I want to get that using spring boot's help. What can I do and how can I overcome this situation?

Thanks

Farhat Shahir
  • 174
  • 1
  • 12

1 Answers1

0

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

Farhat Shahir
  • 174
  • 1
  • 12