39

It is a very basic question. But i am unable to find an answer in Java documentation and unable to test it as well since i don't know if such method exist or not.

I might receive a URL String which could be

http://www.example1.com

or

http://www.example1.com/

and then i will get resource path which might start with /api/v1/status.xml or it would be like api/v1/status.xml

I was looking at URL class and I can handle the first part i.e. fetching the hostURL to make it an HTTPS or HTTP request. The problem is appending the resource path. either i have to check it manually if the first letter is / or not. I was wondering if this functionality is already in some class or not.

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • Is this similar to what you're looking for? It might be helpful: https://stackoverflow.com/questions/1861620/is-there-a-java-package-to-handle-building-urls – MikeB Oct 04 '12 at 15:31

1 Answers1

54
URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Community
  • 1
  • 1
Luke
  • 4,908
  • 1
  • 37
  • 59
  • 1
    What if `URL url = new URL(domain + "files/resource.xml");` ? MalformedURL ? ... what if `domain=www.example.com/` and `new URL (domain + "/files/resources.xml");` ... again malformed – Em Ae Oct 04 '12 at 15:41
  • 1
    I've seen many times where an application first checks the URL string for `if (domain.endsWith("/")) {domain = domain.substring(0, domain.length()-1);}` For all other problems, catch MalformedURLException and handle from there. – Matthew Leidholm Oct 04 '12 at 15:55
  • I'm getting MalformedURLException just because the protocol is not "http". OMG /facepalm – Someone Somewhere Aug 04 '15 at 21:32
  • using java.net.URI is the better way – Someone Somewhere Aug 04 '15 at 21:45