kishore
kishore

Reputation: 1748

Concat two url in java

I have a base url string and another string which should be appended to the base url to get the exact url to request. currently i am using string manipulation to achieve the result. The code i implemented is as follows

private String getUrl(String base, String className){
        try{
            if(!base.endsWith("/")){
                base= base + "/";
            }
            base= base+ base;
            return base;
        }

Is there any inbuilt method to concat the two string directly?

Upvotes: 4

Views: 3005

Answers (1)

isnot2bad
isnot2bad

Reputation: 24444

You can use the java.net.URI class:

URI baseURI = new URI(base + "/");
URI fullURI = baseURI.resolve(className);

URL url = fullURI.toURL(); // as URL
String urlString = fullURI.toString(); // as String

Especially if you can pre-create the base URI once and reuse it multiple times!

Upvotes: 4

Related Questions