Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat two url in java

Tags:

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?

like image 735
kishore Avatar asked Oct 19 '25 10:10

kishore


1 Answers

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!

like image 119
isnot2bad Avatar answered Oct 21 '25 22:10

isnot2bad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!